實現圖片的無縫滾動就是要讓你的圖片集在一定時間里自動切換,那就需要js里的定時器來控制時間。
js中關於定時器的方法有兩種:setTimeout和setInterval。它們接收的參數是一樣的,第一個參數是函數,用於定時器的執行,第二個參數是數字,表示多少毫秒之后執行函數。它們的不同點在於setTimeout只執行一次指定的函數,而setInterval則每隔規定的時間就執行一次指定的函數。
在定時器后面我們還要知道清除定時器的方法:clearTimeout和clearInterval。它們都只接收一個參數,即定時器返回的值,用於消除指定的定時器。
知道定時器以后我們就要想辦法讓圖片動起來,讓圖片元素按一定的速度移位就能實現。可以用js控制元素的樣式,例如:
oUl.style.left = oUl.offsetLeft + speed + 'px';//其中speed的正負可以改變移動的方向。
代碼如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>ZuiYangDan</title> 7 <style> 8 * { 9 margin: 0; 10 padding: 0; 11 list-style: none; 12 } 13 14 #container { 15 width: 100%; 16 border: 1px solid #aaa; 17 margin: 100px 0px; 18 } 19 20 #pictures { 21 width: 100%; 22 height: 520px; 23 overflow: hidden; 24 position: relative; 25 } 26 27 #ul1 { 28 position: absolute; 29 left: 0; 30 top: 0; 31 overflow: hidden; 32 } 33 34 #ul1 li { 35 float: left; 36 width: 700px; 37 height: auto; 38 } 39 40 #ul1 li img { 41 width: 700px; 42 height: auto; 43 } 44 45 </style> 46 <script> 47 window.onload = function() { 48 var oDiv = document.getElementById("pictures"); 49 var oUl = document.getElementById("ul1"); 50 var speed = -3; 51 var oLi = document.getElementsByTagName("li"); 52 53 oUl.innerHTML += oUl.innerHTML;//先把圖片增加一組 54 oUl.style.width = oLi.length * oLi[0].offsetWidth + "px"; 55 56 function move() { 57 if (oUl.offsetLeft < -oUl.offsetWidth / 2) { 58 oUl.style.left = "0"; 59 } 60 oUl.style.left = oUl.offsetLeft + speed + "px"; 61 } 62 var timer = setInterval(move, 30); 63 oDiv.onmouseover = function() { 64 clearInterval(timer); 65 }; 66 oDiv.onmouseout = function() { 67 timer = setInterval(move, 30); 68 }; 69 } 70 71 </script> 72 </head> 73 74 <body> 75 <div id="container"> 76 <div id="pictures"> 77 <ul id="ul1"> 78 <li><img src="./image/P70225-210657.jpg" alt=""></li> 79 <li><img src="./image/P70225-210750.jpg" alt=""></li> 80 <li><img src="./image/P70225-210838.jpg" alt=""></li> 81 <li><img src="./image/P70225-210909.jpg" alt=""></li> 90 </ul> 91 </div> 92 </div> 93 </body> 94 95 </html>
