这是一个可以向左向右滚动的代码,比较简单,容易理解。今天把它整理出来。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 * {margin:0; padding:0;} 8 #div1 {position: relative; border: 1px solid black; width:1100px; height:180px; margin:10px auto; overflow: hidden;} 9 #div1 ul {position: absolute; left:0;} 10 #div1 ul li {list-style: none; float: left; width:200px; height:160px; padding:10px;} 11 #div1 ul li img {width:200px;} 12 #div2 {text-align: center;} 13 14 </style> 15 <script> 16 window.onload=function () { 17 var oDiv=document.getElementById(‘div1‘); 18 var oUl=document.getElementsByTagName(‘ul‘)[0]; 19 var aLi=document.getElementsByTagName(‘li‘); 20 var aA=document.getElementsByTagName(‘a‘); 21 var timer=null; 22 var iSpeed=-8; 23 24 oUl.innerHTML+=oUl.innerHTML; 25 oUl.style.width=aLi.length*aLi[0].offsetWidth+‘px‘; 26 27 function fnMove(){ 28 if(oUl.offsetLeft<-oUl.offsetWidth/2){ //向左滚动 29 oUl.style.left=0+‘px‘; 30 }else if(oUl.offsetLeft>(0)){ //向右滚动 31 oUl.style.left=-oUl.offsetWidth/2+‘px‘; 32 } 33 oUl.style.left=oUl.offsetLeft+iSpeed+‘px‘; 34 } 35 36 timer=setInterval(fnMove, 30); 37 38 aA[0].onclick=function () { 39 iSpeed=-8; 40 } 41 aA[1].onclick=function () { 42 iSpeed=8; 43 } 44 45 oDiv.onmouseover=function () { 46 clearInterval(timer); 47 } 48 oDiv.onmouseout=function () { 49 timer=setInterval(fnMove, 30); 50 } 51 } 52 </script> 53 </head> 54 <body> 55 <div id="div1"> 56 <ul> 57 <li><img src="../images/1.jpg"></li> 58 <li><img src="../images/2.jpg"></li> 59 <li><img src="../images/3.jpg"></li> 60 <li><img src="../images/4.jpg"></li> 61 <li><img src="../images/5.jpg"></li> 62 </ul> 63 </div> 64 <div id="div2"> 65 <a href="javascript:;">向左滚动</a> 66 <a href="javascript:;">向右滚动</a> 67 </div> 68 69 </body> 70 </html>
原文:http://www.cnblogs.com/xiye0324/p/6678223.html