1. 程式人生 > >圖片滾動(待美化)

圖片滾動(待美化)

clear .get mar -1 自加 滾動 com cnblogs tint

1:原有圖片4張,無論向左或者向右滾動,都會出現空白,所以需要在原有4張圖片的基礎下自加得到8張圖片,

技術分享

2:向左滾動:當圖片滾到到整個ul寬度的一半時(aDiv.offsetLeft<-aDiv.offsetWidth/2)

技術分享

將整個ul的左邊距置0(aDiv.style.left=‘0px‘;),通俗說即將整個圖片從左往右第一張圖片拉倒最開始的位置。

技術分享

3:向右滾動:當圖片滾動到ul的左邊距大於0時(aDiv.offsetLeft>0)

技術分享

將整個ul的左邊距設為整個ul寬度的一半(aDiv.style.left=-aDiv.offsetWidth/2+‘px‘)

技術分享

  1 <!DOCTYPE html>
  2 <html>
  3 <head>
  4 <meta charset="utf-8">
  5 <script type="text/javascript">
  6  var timer=null;
  7  var speed=5;
  8  var i=0;
  9  //獲取ID,標簽名
 10  function
getSomething(){ 11 var aBtn1=document.getElementById("btn1"); 12 var aBtn2=document.getElementById("btn2"); 13 var aDiv1=document.getElementById("tu"); 14 var aDiv=aDiv1.getElementsByTagName("ul")[0]; 15 var aLi=document.getElementsByTagName("li"); 16 17 //在原有4張圖片的基礎上自加得到8張圖片
18 aDiv.innerHTML+=aDiv.innerHTML; 19 //ul的寬度為4張圖片寬度 20 aDiv.style.width=aLi[0].offsetWidth*aLi.length+px; 21 //調用圖片滾動函數,默認向左滾動 22 domove(); 23 24 function domove(){ 25 timer=setInterval(function(){ 26 aDiv.style.left=aDiv.offsetLeft-speed+"px"; 27 // 向左滾動時,當圖片滾動到ul寬度的一半時往回拉 28 if(aDiv.offsetLeft<-aDiv.offsetWidth/2) 29 aDiv.style.left=0px; 30 //向右滾動時,當左邊距大於0時,將整個圖片往左拉一半距離。使得左邊不會出現空白 31 else if(aDiv.offsetLeft>0) 32 aDiv.style.left=-aDiv.offsetWidth/2+‘px‘;//x需加上‘px’,否則有錯 33 },30); 34 } 35 //向右滾動 36 aBtn1.onmouseover=function(){ 37 speed=-5; 38 stopMove(); 39 }; 40 //向左滾動 41 aBtn2.onmouseover=function(){ 42 speed=5; 43 stopMove(); 44 }; 45 function stopMove(){ 46 clearInterval(timer); 47 domove(); 48 } 49 50 for(i=0;i<aLi.length;i++) 51 { 52 //當鼠標移動到圖片上時,停止滾動 53 aLi[i].onmouseover=function () 54 { 55 clearInterval(timer); 56 }; 57 //當鼠標移出到圖片時,繼續滾動 58 aLi[i].onmouseout=function () 59 { 60 domove(); 61 }; 62 } 63 64 } 65 </script> 66 <style> 67 *{ 68 padding:0; 69 margin:0; 70 } 71 li{ 72 list-style: none; 73 } 74 img{ 75 border:0; 76 } 77 78 #tu{ 79 width:550px; 80 height:108px; 81 /*!!!*/ 82 overflow: hidden; 83 margin:0 auto; 84 position: relative; 85 left:0; 86 } 87 #tu ul{ 88 position: absolute; 89 top:0; 90 /*滾動的原理即改變ul的左邊距*/ 91 left: 0px; 92 } 93 #tu li{ 94 width:183px; 95 height:108px; 96 float:left; 97 } 98 </style> 99 </head> 100 <body onload="getSomething();"> 101 <input id="btn1" type="button" value="向右滾動"> 102 <input id="btn2" type="button" value="向左滾動"> 103 <div id="tu"> 104 <ul> 105 <li><img src="images/1.jpg"></li> 106 <li><img src="images/2.jpg"></li> 107 <li><img src="images/3.jpg"></li> 108 <li><img src="images/4.jpg"></li> 109 </ul> 110 </div> 111 </body> 112 </html>

aDiv.style.left=‘0px‘;

圖片滾動(待美化)