門戶網站好多都有產品無線滾動展示的效果:css
測試demo1 -- 非無縫滾動(能夠看出來從頭開始的效果):html
css樣式以下:測試
.box{ width: 1000px; border: 1px solid #ccc; overflow: hidden; height: 110px; margin: 50px auto; white-space: nowrap; position: relative; } .con1{ width: 1000px; height: 110px; overflow: hidden; position: absolute; left: 0; } .con2{ position: absolute; overflow: hidden; opacity: 0; }
html代碼以下:網站
<div class="box"> <div class="con1"> <li><img src="img/SD_1.jpg" alt=""></li> <li><img src="img/SD_2.jpg" alt=""></li> <li><img src="img/SD_3.jpg" alt=""></li> <li><img src="img/SD_4.jpg" alt=""></li> <li><img src="img/SD_5.jpg" alt=""></li> <li><img src="img/SD_6.jpg" alt=""></li> </div> <div class="con2"></div> </div>
js代碼以下:spa
window.onload = function(){ var cont = 5; //時間間隔 var box = document.getElementsByClassName("box")[0]; var con1 = document.getElementsByClassName("con1")[0]; var con2 = document.getElementsByClassName("con2")[0]; con2.innerHTML = con1.innerHTML; function scroll(){ if(con1.scrollLeft >= con2.offsetWidth - box.offsetWidth){ //利用滾動差當滾動不動時重置爲0 con1.scrollLeft = 0; }else{ con1.scrollLeft += 1; } } var timer = setInterval(scroll,cont); box.onmouseover = function(e){ clearInterval(timer); } box.onmouseout = function(e){ timer = setInterval(scroll,cont); } }
2.測試demo2 -- 無縫滾動效果,看不出來重0效果:code
css代碼以下:htm
.box{ width: 1000px; border: 1px solid #ccc; overflow: hidden; height: 110px; margin: 50px auto; white-space: nowrap; position: relative; } .con1,.con2{ display: inline; }
html結構同上;blog
js代碼以下:seo
window.onload = function(){ var cont = 5; var box = document.getElementsByClassName("box")[0]; var con1 = document.getElementsByClassName("con1")[0]; var con2 = document.getElementsByClassName("con2")[0]; con2.innerHTML = con1.innerHTML; function scroll(){ if(con2.offsetWidth - box.scrollLeft <= 0){ // box.scrollLeft = 0; //重置爲0 (這兩項都行,不太明白???) // box.scrollLeft -= con1.offsetWidth; //此值非0 通常狀況爲負值 (效果和重置爲0同樣) }else{ box.scrollLeft += 1; } } var timer = setInterval(scroll,cont); box.onmouseover = function(e){ clearInterval(timer); } box.onmouseout = function(e){ timer = setInterval(scroll,cont); } }