Baidu skin changing effect
analysis:
Using a loop to register click events for a set of elements
When the mouse passes a picture, the current page background is replaced by the passing picture. After the mouse is removed, the default
When the image is clicked, the current page background is changed to the clicked image
Core algorithm: take the src path of the current picture and give the body as the background
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } body { background: url(images/bg1.jpg) no-repeat center top; } li { list-style: none; } .baidu { overflow: hidden; margin: 100px auto; background-color: #fff; width: 410px; padding-top: 3px; } .baidu li { float: left; margin: 0 1px; cursor: pointer; } .baidu img { width: 100px; } </style> </head> <body> <ul class="baidu"> <li><img src="images/bg1.jpg" alt=""></li> <li><img src="images/bg2.jpg" alt=""></li> <li><img src="images/bg3.jpg" alt=""></li> <li><img src="images/bg4.jpg" alt=""></li> </ul> <script> //Get element var images = document.querySelector('.baidu').querySelectorAll('img'); for (var i = 0; i < images.length; i++) { //temp stores the original background var temp; images[i].onclick = function () { document.body.style.backgroundImage = 'url(' + this.src + ')'; temp = 'url(' + this.src + ')'; } images[i].onmouseover = function () { temp = document.body.style.backgroundImage; document.body.style.backgroundImage = 'url(' + this.src + ')'; } images[i].onmouseout = function () { document.body.style.backgroundImage = temp; } } </script> </body> </html>
Form select all cancel select all
analysis:
Click the check boxes above to select all, and all the check boxes below are selected (select all)
Click the select all check box again, and none of the following check boxes will be selected (unselect all)
If the check boxes below are all selected, the select all button above is automatically selected
If one of the check boxes below is not selected, the select all button above is not selected
All check boxes are not selected by default at the beginning
The following check boxes need to be selected, and the above check boxes can only be selected: bind the click event to all the check boxes below, and check whether all the check boxes below are selected or not every time you click. If there is an unselected check box above, select none.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> table { width: 800px; height: 500px; margin: 0 auto; border: 1px solid #999; text-align: center; } table tbody tr { background-color: rgb(163, 163, 163); } thead { background-color: skyblue; } </style> </head> <body> <table> <thead> <tr> <th><input type="checkbox" name="" id="checkAll" ></th> <th>commodity</th> <th>Price</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox" name="" id=""></td> <td>iPhone Xs Max</td> <td>10000</td> </tr> <tr> <td><input type="checkbox" name="" id=""></td> <td>iPad Pro</td> <td>5000</td> </tr> <tr> <td><input type="checkbox" name="" id=""></td> <td>iWatch</td> <td>3000</td> </tr> <tr> <td><input type="checkbox" name="" id=""></td> <td>AirPods</td> <td>1000</td> </tr> </tbody> </table> <script> var checkAll = document.querySelector('#checkAll'); var trs = document.querySelector('tbody').querySelectorAll('tr'); var tbCheck = document.querySelector('tbody').getElementsByTagName('input'); for (var i = 0; i < trs.length; i++) { trs[i].onmouseover = function () { this.style.backgroundColor = 'rgb(200, 200, 200)'; } trs[i].onmouseout = function () { this.style.backgroundColor = ''; } } checkAll.onclick = function () { for (var j = 0; j < tbCheck.length; j++) { tbCheck[j].checked = checkAll.checked; } } //Select all of the following, and select the above for (var i = 0; i < tbCheck.length; i++) { tbCheck[i].onclick = function () { // flag controls whether the select all button is selected var flag = true; for (var j = 0; j < tbCheck.length; j++) { if (!(tbCheck[j].checked)) { flag = false; break; // Exit for loop to improve operation efficiency } } checkAll.checked = flag; } } </script> </body> </html>
TAB case (key)
analysis:
A big box, two small boxes inside
In the above module, after clicking a certain one, the background color of this one is red, and the rest is gray (exclusive thought)
After clicking a certain module, the corresponding content of the module will be displayed, and other hidden contents will be written into the click event
The display below corresponds to the small li above one by one
Core idea:
Give the tab above_ List add custom property, property number starts from 0
When you click on the module above, the display module of the formation below will be displayed, and the others will be hidden
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } ul { list-style: none; } .tab { width: 800px; height: 500px; margin: 200px auto; } .tab_list { height: 50px; background-color: rgb(162, 162, 162); border-bottom: 2px solid #c81623; } .tab_list ul li { float: left; display: inline-block; width: 150px; height: 50px; line-height: 50px; text-align: center; cursor: pointer; } .tab_list .current { background-color: #c81623; color: #fff; } .item { display: none; } </style> </head> <body> <div class="tab"> <div class="tab_list"> <ul> <li class="current">Product introduction</li> <li>Specifications and packaging</li> <li>After sales support</li> <li>Commodity evaluation(1.1ten thousand+)</li> <li>Mobile community</li> </ul> </div> <div class="tab_con"> <div class="item" style="display: block"> //Product introduction module content </div> <div class="item"> //Specification and packaging module content </div> <div class="item"> //After sales support module content </div> <div class="item"> //Content of commodity evaluation module </div> <div class="item"> //Mobile community module content </div> </div> </div> <script> var tab_list = document.querySelector('.tab_list'); var lis = tab_list.querySelectorAll('li'); var items = document.querySelectorAll('.item'); for (var i = 0; i < lis.length; i++) { //Set index number for 5 li lis[i].setAttribute('index', i); lis[i].onclick = function () { //Kill the others for (var j = 0; j < lis.length; j++) { lis[j].className = ''; } this.className = 'current'; var index = this.getAttribute('index'); for (var k = 0; k < items.length; k++) { items[k].style.display = 'none'; } items[index].style.display = 'block'; } } </script> </body> </html>
Sina pull down menu
Analysis: there are ul and li in nav navigation bar, and then there are ul and li under li. The second layer ul and li are displayed when the mouse is moved up
li in the navigation bar must have the effect of mouse passing, so it needs to be registered circularly
Core principle: when the mouse passes li, the child's ul and li are displayed, and when the mouse leaves, they are hidden
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Sina.com</title> <style> * { margin: 0; padding: 0; } ul { list-style: none; } a { text-decoration: none; } .nav { width: 800px; margin: 200px auto; position: relative; } .nav>li { width: 80px; height: 100%; line-height: 41px; color: #333; float: left; position: relative; text-align: center; } .nav>li>a:hover { background-color: #eee; } .nav li ul { display: none; position: absolute; top: 41px; left: 0; width: 100%; border-left: 1px solid #fecc5b; border-right: 1px solid #fecc5b; box-sizing: border-box; } .nav li ul li { border-bottom: 1px solid #fecc5b; /* width: 50px; text-align: center; */ } .nav ul li a:hover { background-color: #FFF5DA; } </style> </head> <body> <ul class="nav"> <li> <a href="#">micro-blog</a> <ul> <li> <a href="#">private letter</a> </li> <li> <a href="#">comment</a> </li> <li> <a href="#">@I</a> </li> </ul> </li> <li> <a href="#">micro-blog</a> <ul> <li> <a href="#">private letter</a> </li> <li> <a href="#">comment</a> </li> <li> <a href="#">@I</a> </li> </ul> </li> <li> <a href="#">micro-blog</a> <ul> <li> <a href="#">private letter</a> </li> <li> <a href="#">comment</a> </li> <li> <a href="#">@I</a> </li> </ul> </li> </ul> <script> //Get element var nav = document.querySelector('.nav'); var lis = nav.children; //Circular registration event for (var i = 0; i < lis.length; i++) { lis[i].onmouseover = function () { this.children[1].style.display = 'block'; } lis[i].onmouseout = function () { this.children[1].style.display = 'none'; } } </script> </body> </html>
Message board cases
analysis:
Page composition: a text field, a submit button, a message board
When clicking the submit button, first judge whether the content of the text field is empty. If it is empty, it will be warned
If it is not empty, create a new li, assign the content of the text field to li, and then add li in front of ul
Add functions based on message board cases
When the content magnitude of the text field is given to li, an additional deleted link is added,
Loop to get all links. When we click a link, delete the li of the current link
J needs to be added to prevent link jump avascript:void (0); or javascript:;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Sina.com</title> </head> <style> ul { margin-top: 50px; } li { width: 3oopx; padding: 5px; background-color: aliceblue; color: red; font-size: 14px; margin: 15px 0; } li a { float: right; } </style> <body> <textarea name="" id=""></textarea> <button>Leaving a message.</button> <ul> </ul> <script> //Get element var btn = document.querySelector('button'); var text = document.querySelector('textarea'); var ul = document.querySelector('ul'); //Register events btn.onclick = function () { if (text.value == '') { alert('You have not entered anything'); return false; } else { var li = document.createElement('li'); //Assign the content of the text field to li, and then add a link to delete the message li.innerHTML = text.value + "<a href='javascript:;'>delete</a>"; ul.insertBefore(li, ul.children[0]); text.value = ''; var as = document.querySelectorAll('a'); for (var i = 0; i < as.length; i++) { as[i].onclick = function () { //The current li of a is deleted ul.removeChild(this.parentNode); } } } } </script> </body> </html>
Press the s key to locate the search box:
Check whether the user presses the s key. If the s key is pressed, position the cursor in the search box.
analysis:
Using the keyCode in the keyboard event object to determine whether the user presses the s key
How to get the focus of search box: using the focus() method in js
<!DOCTYPE html> <html lang="en"> <head> <title>Jingdong search box</title> </head> <body> <input type="text" name="" id=""> <script> var input = document.querySelector('input'); document.addEventListener('keyup', function (e) { if (e.keyCode == 83) { input.focus(); } }); </script> </body> </html>
Automatically jump to page after 5 seconds
analysis:
Use timer to make countdown effect
location.href Jump page
<div>Will be in5Seconds later, jump to the home page!</div> <script> setTimeout(function() { location.href = 'http://www.baidu.com'; }, 5000); </script>
Get the mouse position in the box
analysis:
We move the mouse inside the box to get the distance between the left and the top of the box
First get the coordinates of the mouse in the page (e.pagex and e.pagey)
Next, get the box's distance in the page (box. Offsetleft and box. Offsettop)
Subtracting the distance between the box and the page border from the coordinates of the mouse distance from the page is the coordinates of the mouse in the box
<div class="box"></div> <script> var box = document.querySelector('.box'); box.addEventListener('mousemove', function(e) { var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; box.innerHTML = ('X The coordinates are' + x + 'ï¼›Y The coordinates are' + y); }); </script>
Drag mode box
Case requirements:
- Click the pop-up layer, the modal box will pop up, and the gray translucent test occlusion layer will be displayed
- Click the close button to close the modal box and close the gray translucent mask at the same time
- Place the mouse on the top row of the modal box, and drag the modal box to move in the page with the mouse held down
- Release the mouse and the modal box stops moving
Case study:
- Click the pop-up layer, and the modal box and occlusion layer will be displayed display:block
- Click the close button, and the modal box and occlusion layer will be hidden display:none
- Principle of dragging in the page: press and move the mouse, release the mouse, starting event: press mousedown, move mousemove, release the mouse
mouseup - The event source triggered by mouse click is the top line, that is, the id is title
- The real coordinates of the modal box are the coordinates of the mouse minus the coordinates of the mouse in the box
Jingdong magnifier effect
Case requirements:
The case can be divided into three functional modules
- The mouse passes through the small picture box, the Yellow mask and the large picture box, leaving the hidden two boxes
- Yellow occlusion follows the mouse
- Move the Yellow mask and follow the big picture
Case study:
Yellow occlusion follows the mouse function.
It's not appropriate to give the mouse coordinates to the occlusion layer. Because the occlusion coordinates are based on the parent box.
The first is to get the coordinates of the mouse in the box.
Then the value is given to the occlusion layer as left and top values.
At this time, use the mouse to move the event, but still move in the small picture box.
It is found that the position of the occlusion layer is not correct, and it is necessary to subtract half of the height and width of the box itself.
The occlusion layer cannot exceed the range of small picture box.
If it is less than zero, set the coordinates to 0
If it is greater than the maximum moving distance of the occlusion layer, set the coordinate to the maximum moving distance
Maximum moving distance of occlusion: small picture box width minus occlusion box width
Moving distance of big picture = moving distance of occlusion layer * maximum moving distance of big picture / maximum moving distance of occlusion layer
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } .preview_img { position: relative; width: 402px; height: 402px; } .preview_img img { width: 400px; height: 400px; } .mask { display: none; position: absolute; width: 300px; height: 300px; top: 0; left: 0; background-color: #FEDE4F; opacity: .5; cursor: move; border: 1px solid #ccc; overflow: hidden; } .big { display: none; position: absolute; width: 600px; height: 600px; top: 0; left: 410px; z-index: 999; background-color: pink; border: 1px solid #ccc; overflow: hidden; } .big img { position: absolute; top: 0; left: 0; width: 800px; height: 800px; } </style> </head> <body> <div class="preview_img"> <img src="./a.jpg" alt=""> <div class="mask"></div> <div class="big"> <img src="./a.jpg" alt="" class="bigImg"> </div> </div> <script> var preview_img = document.querySelector('.preview_img'); var mask = document.querySelector('.mask'); var big = document.querySelector('.big'); preview_img.addEventListener('mouseover', function () { mask.style.display = 'block'; big.style.display = 'block'; }); preview_img.addEventListener('mouseout', function () { mask.style.display = 'none'; big.style.display = 'none'; }); //When the mouse moves, let the mouse follow the yellow box preview_img.addEventListener('mousemove', function (e) { var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; var maskX = x - mask.offsetWidth / 2; var maskY = y - mask.offsetHeight / 2; var maskMax = preview_img.offsetWidth - mask.offsetWidth; if (maskX < 0) { maskX = 0; } else if (maskX >= maskMax) { maskX = maskMax; } if (maskY < 0) { maskY = 0; } else if (maskY >= maskMax) { maskY = maskMax; } mask.style.left = maskX + 'px'; mask.style.top = maskY + 'px'; var bigImg = document.querySelector('.bigImg'); var bigMax = bigImg.offsetWidth - big.offsetWidth; var bigX = maskX * bigMax / maskMax; var bigY = maskY * bigMax / maskMax; bigImg.style.left = -bigX + 'px'; bigImg.style.top = -bigY + 'px'; }); </script> </body> </html>
Countdown effect
analysis:
This countdown is constantly changing, so use setInterval() to implement
Each of the three black boxes is placed in minutes and seconds
Hours, minutes and seconds of three black boxes using innerHTML
Before the first refresh, it is also a certain number of milliseconds, so call the refresh time function in front of the timer to prevent the blank before the first refresh
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { margin: 200px 200px; } div span { display: inline-block; width: 50px; height: 50px; font-size: 26px; background-color: #666; color: #fff; line-height: 50px; text-align: center; } </style> </head> <body> <div> <span class="hour">1</span> <span class="minute">2</span> <span class="second">3</span> </div> <script> var hour = document.querySelector('.hour'); var minute = document.querySelector('.minute'); var second = document.querySelector('.second'); var inputTime = +new Date('2020-7-22 18:00:00'); // Run once before timer acquisition so that the original default 1 2 3 is not displayed getInterval(); // Get events every second setInterval(getInterval, 1000); function getInterval() { var nowTime = +new Date(); var interval = (inputTime - nowTime) / 1000; //Seconds between two dates var hours, minutes, seconds; hours = Math.floor(interval / 60 / 60 % 24); hours = hours < 10 ? '0' + hours : hours; hour.innerHTML = hours; minutes = Math.floor(interval / 60 % 60); minutes = minutes < 10 ? '0' + minutes : minutes; minute.innerHTML = minutes; seconds = Math.floor(interval % 60); seconds = seconds < 10 ? '0' + seconds : seconds; second.innerHTML = seconds; } </script> </body> </html>
Clear timer
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button class="begin">Start timer</button> <button class="stop">End timer</button> <script> var i = 1; var begin = document.querySelector('.begin'); var stop = document.querySelector('.stop'); var timer = null; //Global variable, null is an empty object begin.addEventListener('click', function() { timer = setInterval(function() { console.log('How do you do' + i); i = i + 1; }, 1000); }); stop.addEventListener('click', function() { clearInterval(timer); }); </script> </body> </html>
Send SMS case
After clicking the send verification code, the button can only be clicked again in 60 seconds to prevent repeated sending of SMS
analysis
After clicking the button, disable the button to true
Modify the contents of button once a second
Define a variable as the number of seconds, which changes periodically. If it is 0, it means the time is up, and the button returns to its original state
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> //phone number: <input type="number" name="" id=""> <button>send out</button> <script> var btn = document.querySelector('button'); btn.addEventListener('click', function() { btn.disabled = true; var i = 60; var timer = setInterval(function() { if (i == 0) { clearInterval(timer); btn.disabled = false; btn.innerHTML = 'Send verification code'; i = 60; } else { btn.innerHTML = i + 'Seconds later, you can click again'; i--; } }, 1000); }); </script> </body> </html>
Dynamically generate tables
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> table { border: 1px solid #666; margin: 200px auto; } th, td { border: 1px solid #666; } thead tr { background-color: #ccc; height: 80px; } td { width: 120px; text-align: center; height: 36px; line-height: 36px; } </style> </head> <body> <table cellspacing="0"> <thead> <tr> <th>full name</th> <th>subject</th> <th>achievement</th> <th>operation</th> </tr> </thead> <tbody> </tbody> </table> <script> //To put a series of objects in an array var datas = [{ name: 'Zhang San', subject: 'JavaScript', score: '100' }, { name: 'Li Si', subject: 'JavaScript', score: '93' }, { name: 'Wang Wu', subject: 'JavaScript', score: '85' } ]; //Create a row in tbody, and determine the number of rows by the length of the array var tbody = document.querySelector('tbody'); for (var i = 0; i < datas.length; i++) { //That's ok //Create tr row var tr = document.createElement('tr'); tbody.appendChild(tr) //Create cell td in row //The number of cells depends on the number of properties in each object. for loops through objects for (var k in datas[i]) { //column var td = document.createElement('td'); //Give the attribute value in the object to td //console.log(datas[i][k]); td.innerHTML = datas[i][k]; tr.appendChild(td); } //Create a cell with two words removed var td = document.createElement('td'); td.innerHTML = "<a href='javascript:;'>delete</a>"; tr.appendChild(td); } //Delete operation var as = document.querySelectorAll('a'); for (var i = 0; i < as.length; i++) { as[i].onclick = function () { //Click a to delete the line where a is. This line is the father of A tbody.removeChild(this.parentNode.parentNode); } } /* var (var k in obj) { k Is the property name obj[k] Is the property value } */ </script> </body> </html>
Imitating Taobao to fix the right sidebar
analysis:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .slider-bar { position: absolute; left: 50%; top: 300px; margin-left: 600px; width: 45px; height: 130px; background-color: pink; } .w { width: 1200px; margin: 10px auto; } .header { height: 150px; background-color: purple; } .banner { height: 250px; background-color: skyblue; } .main { height: 1000px; background-color: yellowgreen; } span { display: none; position: absolute; bottom: 0; } </style> </head> <body> <div class="slider-bar"> <span class="goBack">Back to top</span> </div> <div class="header w">Head area</div> <div class="banner w">banner region</div> <div class="main w">Main part</div> <script> // 1, Get element var sliderbar = document.querySelector('.slider-bar'); var banner = document.querySelector('.banner'); // banner.offsetTop It's the size of the head being rolled off, and it must be written to the scrolling outer code var bannerTop = banner.offsetTop // The value that should change when our sidebar is fixed var sliderbarTop = sliderbar.offsetTop - bannerTop; // Get main body element var main = document.querySelector('.main'); var goBack = document.querySelector('.goBack'); var mainTop = main.offsetTop; // 2. Page scrolling event scroll document.addEventListener('scroll', function () { // window.pageYOffset The head of the page being rolled // 3. When the head of our page is larger than or equal to 172, the sidebar will be fixed if (window.pageYOffset >=172 ){ sliderbar.style.position = 'fixed'; sliderbar.style.top = sliderbarTop + 'px'; } else { sliderbar.style.position = 'absolute' sliderbar.style.top = '300px'; } // 4. When we scroll to the main box, the goBack module is displayed if (window.pageYOffset >= mainTop) { goBack.style.display = 'block'; } else { goBack.style.display = 'none'; } }) </script> </body> </html>
pc web page carousel
analysis:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> *{ margin: 0; padding: 0; } .main { width: 980px; height: 455px; margin-left: 219px; margin-top: 10px; } .focus { position: relative; width: 720px; height: 455px; background-color: purple; overflow: hidden; } .focus ul { width: 600%; position: absolute; top: 0; left: 0; } .focus ul li { float: left; } .arrow-l, .arrow-r { display: none; position: absolute; top: 50%; margin-top: -20px; width: 24px; height: 40px; background: rgba(0, 0, 0, .3); text-align: center; line-height: 40px; color: #ffffff; font-family: 'icomoon'; font-size: 18px; z-index: 2; } .arrow-r { right: 0; } .circle { position: absolute; bottom: 10px; left: 50px; list-style: none; } .circle li { float: left; width: 8px; height: 8px; border: 2px solid grey; margin: 0 3px; border-radius: 50%; cursor: pointer; } .current { background-color: #ffffff; } .photo li img { width: 720px; height:455px; } </style> <script src="index.js"></script>` <body> <div class="w"> <div class="main"> <div class="focus f1"> <!--Left button--> <a href="javascript:" class="arrow-l"> < </a> <!--Right button--> <a href="javascript:" class="arrow-r"> > </a> <!--Core scrolling area--> <ul class="photo"> <li> <a href="#"><img src="a.jpg" alt=""></a> </li> <li> <a href="#"><img src="b.jpg" alt=""></a> </li> <li> <a href="#"><img src="a.jpg" alt=""></a> </li> <li> <a href="#"><img src="b.jpg" alt=""></a> </li> </ul> <!--Small circle--> <ol class="circle"> </ol> </a> </div> </div> </div> </body> </html>
// index.js window.addEventListener('load', function() { // 1. Get element var arrow_l = this.document.querySelector('.arrow-l'); var arrow_r = this.document.querySelector('.arrow-r'); var focus = document.querySelector('.focus'); var focusWidth = focus.offsetWidth; // 2. Mouse over focus to show hidden left and right buttons focus.addEventListener('mouseenter', function() { arrow_l.style.display = 'block'; arrow_r.style.display = 'block'; clearInterval(timer); timer = null; // Clear timer variable }) focus.addEventListener('mouseleave', function() { arrow_l.style.display = 'none'; arrow_r.style.display = 'none'; timer = setInterval(function() { // Call click event manually arrow_r.click(); }, 2000); }); // 3. Generate small circles dynamically, and generate several small circles when there are several graphs var ul = focus.querySelector('ul'); var ol = focus.querySelector('.circle'); for (var i = 0; i < ul.children.length; i++) { // Create a small li var li = document.createElement('li'); // Record the index number of the current small circle through the custom attribute li.setAttribute('index', i) // Insert little li into ol ol.appendChild(li); // 4. The exclusive thought of small circles, we can directly generate small circles and bind click events at the same time li.addEventListener('click', function() { // Clear the current class name of all small li for (var i = 0;i < ol.children.length; i++) { ol.children[i].className = ''; } //Current class name is set by current small li this.className = 'current'; // 5. Click the small circle, move the picture, of course, ul // ul's moving distance = index number of small circle * picture width, note negative value // When we click a small li, we get the index number of the current small li var index = this.getAttribute('index'); // When we click a small li, we need to give the index number of li to num num = index; // When we click on a small li, we need to give the index number of li to circle circle = index; animate1(ul, -index * focusWidth); }) } // Set the first small li in ol to the class name current ol.children[0].className = 'current'; // 6. Clone the first picture (li) and put it at the back of ul var first = ul.children[0].cloneNode(true); ul.appendChild(first); // 7. Click the button on the right to scroll one picture var num = 0; // circle controls the playback of small circles var circle = 0; // throttle valve var flag = true; arrow_r.addEventListener('click', function() { if(flag) { flag = false; // Close the throttle valve // If we go to the last copied image, our ul will quickly restore left to 0 if (num == ul.children.length - 1) { ul.style.left = 0; num = 0; } num++; animate1(ul, -num * focusWidth, function() { flag = true; // Open throttle valve }); // 8. Click the button on the right, and the small circle will change together. You can declare another variable to control the small circle to play circle++; // If circle == 4 indicates that we have reached the end of the cloned image, we will restore it if (circle == ol.children.length) { circle = 0; } circleChange(); } }) // 9. Left button method arrow_l.addEventListener('click', function() { if(flag) { flag = false; // Close the throttle valve // If we go to the last copied image, our ul will quickly restore left to 0 if (num == 0) { num = ul.children.length - 1; ul.style.left = -num * focusWidth + 'px'; } num--; animate2(ul, -num * focusWidth, function() { flag = true; // Open throttle valve }); // 8. Click the button on the right, and the small circle will change together. You can declare another variable to control the small circle to play circle--; // If circle < 0 means to go to the last picture, the small circle should be changed to the fourth small circle (3) //if (circle < 0) { // circle = ol.children.length - 1; //} circle = circle < 0 ? ol.children.length - 1 : circle; circleChange(); } }); function circleChange() { // Clean up the current class names of the rest of the small circles first for (var i = 0; i< ol.children.length; i++) { ol.children[i].className = ''; } // Leave the current class name of the current small circle ol.children[circle].className = 'current'; } // 10. Auto play carousel var timer = setInterval(function() { // Call click event manually arrow_r.click(); }, 3000); function animate1(obj, target, callback) { clearInterval(obj.timer) obj.timer = setInterval(function() { // Step value written to timer // Change our step size to integer, so as to avoid the problem of decimals var step = Math.floor((target - obj.offsetLeft) / 10); //step = step > 0 ? Math.ceil(step) : Math.floor(step); if (obj.offsetLeft == target) { // Stop animation, essentially stop timer clearInterval(obj.timer); // Callback function written to the end of timer if (callback) { // Call function callback(); } } // Change the step value of adding 1 each time to a slowly decreasing value. Step formula: (target value - current position) / 10 obj.style.left = obj.offsetLeft + step + 'px'; }, 15) } function animate2(obj, target, callback) { clearInterval(obj.timer) obj.timer = setInterval(function() { // Step value written to timer // Change our step size value to integer without decimal problem var step = Math.ceil((target - obj.offsetLeft) / 10); //step = step > 0 ? Math.ceil(step) : Math.floor(step); if (obj.offsetLeft == target) { // Stop animation, essentially stop timer clearInterval(obj.timer); // Callback function written to the end of timer if (callback) { // Call function callback(); } } // Change the step value of adding 1 each time to a slowly decreasing value. Step formula: (target value - current position) / 10 obj.style.left = obj.offsetLeft + step + 'px'; }, 15) } });
Carousel map of mobile terminal
analysis:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> *{ margin: 0; padding: 0; } .focus { position: relative; padding-top: 44px; } .focus img { width: 100%; } .focus ul { overflow: hidden; width: 500%; margin-left: -100%; } .focus ul li { float: left; width: 20%; } .focus ol { position: absolute; bottom: 5px; right: 5px; margin: 0; } .focus ol li { display: inline-block; width: 5px; height: 5px; background-color: red; list-style: none; border-radius: 2px; transition: all .3s; } .focus ol li.current { width: 15px; } </style> <script src="index.js"></script>` <body> <div class="focus"> <ul> <li><img src="./c.jpg" alt=""></li> <li><img src="./a.jpg" alt=""></li> <li><img src="./b.jpg" alt=""></li> <li><img src="./c.jpg" alt=""></li> <li><img src="./a.jpg" alt=""></li> </ul> <ol> <li class="current"></li> <li></li> <li></li> </ol> </div> </body> </html>
// index.js window.addEventListener('load', function() { // 1. Get element var focus = document.querySelector('.focus'); var ul = focus.children[0]; // Get the width of focus var w = focus.offsetWidth; var ol = focus.children[1]; // 2. Using timer to automatically rotate pictures var index = 0; var timer = setInterval(function() { index++; var translatex = -index * w; ul.style.transition = 'all .3s'; ul.style.transform = 'translateX(' + translatex + 'px)'; }, 2000); // Wait for the transition to be completed before judging and listening for the transition event: transition end ul.addEventListener('transitionend', function() { // Seamless scrolling if (index >= 3) { index = 0; // Remove the transition effect, so that our ul can quickly jump to the target position ul.style.transition = 'none'; // Use the latest index number times the width to scroll the picture var translatex = -index * w; ul.style.transform = 'translateX(' + translatex + 'px)'; } else if (index < 0) { index = 2; ul.style.transition = 'none'; // Use the latest index number times the width to scroll the picture var translatex = -index * w; ul.style.transform = 'translateX(' + translatex + 'px)'; } }) // 3. Small dots follow // Select the li in ol with current class name and remove the class name remove ol.querySelector('.current').classList.remove('current'); // Add current add to the small li of the current index number ol.children[index].classList.add('current'); // 4. Finger slide carousel // Touch the element touchstart to get the initial coordinates of fingers var startX = 0; var moveX = 0; // We will use this moving distance later, so we need to define a global variable var flag = false; ul.addEventListener('touchstart', function(e) { startX = e.targetTouches[0].pageX; clearInterval(timer); }); // Move finger touchmove: calculates the sliding distance of the finger and moves the box ul.addEventListener('touchmove', function(e) { // Calculate the moving distance moveX = e.targetTouches[0].pageX - startX; // Move the box: the original position of the box + the distance the finger moves var translatex = -index * w + moveX; // You don't need animation when you drag your fingers, so you need to cancel the transition effect ul.style.transition = 'none'; ul.style.transform = 'translateX(' + translatex + 'px)'; flag = true; // How to judge the movement effect after the user's fingers have been moved, otherwise no judgment will be made e.preventDefault(); // Prevent screen scrolling }) // When the fingers leave, judge whether to rebound or play the previous one or the next one according to the moving distance ul.addEventListener('touchend', function(e) { // If the moving distance is greater than 50 pixels, play the previous or next picture if(flag) { if (Math.abs(moveX) > 50) { // If it's a right slide, it's playing the previous one. moveX is a positive value if (moveX > 0) { index--; } else { // If it's left slide, it's playing the next one, and moveX is negative index++; } var translatex = -index * w; ul.style.transition = 'all .3s'; ul.style.transform = 'translateX(' + translatex + 'px)'; } // Turn on the timer again when the fingers leave clearInterval(timer); timer = setInterval(function() { index++; var translatex = -index * w; ul.style.transition = 'all .3s'; ul.style.transform = 'translateX(' + translatex + 'px)'; }, 2000); } }) })
Remember user name cases
analysis:
- Store the data and use it for local storage
- Close the page, and the user name can also be displayed, so localStorage is used
- Open the page, first judge whether there is this user name, if so, display the user name in the form, and check the box
- change event when the check box changes
- Store if checked, otherwise remove
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input type="text" id="username"><input type="checkbox" name="" id="remember">Remember user name <script> var username = document.querySelector('#username'); var remember = document.querySelector('#remember'); if(localStorage.getItem('username')) { username.value = localStorage.getItem('username'); remember.checked = true; } remember.addEventListener('change', function() { if (this.checked) { localStorage.setItem('username', username.value) } else { localStorage.removeItem('username'); } }) </script> </body> </html>