間歇、無縫滾動效果(用gif錄制的效果不是很好,有興趣的可以down代碼),具體內容如下
代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>無縫滾動</title> <style> *{margin:0;padding:0;} .box{width: 500px;height: 400px;margin:40px auto;background: #ccc;overflow: hidden;} .block{position: relative;width: 500px;height: 400px;overflow: hidden;} .item{height: 40px;background: red;color: #fff;line-height: 40px;text-align: center;} .item:nth-child(2n){background: #000} </style> <script> var scrollUp=(function(){ return function(json){ var objScroll = document.getElementById(json.id); objScroll.scrollTop = 0; objScroll.innerHTML += objScroll.innerHTML; if(json.on){ function scrollIng(){ if(objScroll.scrollTop >= objScroll.scrollHeight) { objScroll.scrollTop = 0; }else{ objScroll.scrollTop ++; } } var myScroll = setInterval(function(){scrollIng()},30); objScroll.onmouseover = function(){ clearInterval(myScroll); } objScroll.onmouseout = function(){ myScroll = setInterval(function(){scrollIng()},30); } }else{ var timer; function startScroll(){ timer=setInterval(function(){scrollUp()},30); objScroll.scrollTop++; } function scrollUp(){ if(objScroll.scrollTop % json.height==0){ clearInterval(timer); setTimeout(startScroll,2000); }else{ objScroll.scrollTop++; if(objScroll.scrollTop >= objScroll.scrollHeight/2){ objScroll.scrollTop =0; } } } setTimeout(startScroll,1000); } } })() window.onload=function(){ //on:間歇滾動/無縫滾動 height:間歇滾動的高度 scrollUp({on:true,id:'block'}); scrollUp({id:'block2',height:120}); } </script> </head> <body> <div class="box"> <div class="block" id="block"> <div class="item">1無縫滾動</div> <div class="item">2無縫滾動</div> <div class="item">3無縫滾動</div> <div class="item">4無縫滾動</div> <div class="item">5無縫滾動</div> <div class="item">6無縫滾動</div> <div class="item">7無縫滾動</div> <div class="item">8無縫滾動</div> <div class="item">9無縫滾動</div> <div class="item">10無縫滾動</div> <div class="item">11無縫滾動</div> <div class="item">12無縫滾動</div> <div class="item">13無縫滾動</div> <div class="item">14無縫滾動</div> <div class="item">15無縫滾動</div> </div> </div> <div class="box"> <div class="block" id="block2"> <div class="item">1間歇滾動</div> <div class="item">2間歇滾動</div> <div class="item">3間歇滾動</div> <div class="item">4間歇滾動</div> <div class="item">5間歇滾動</div> <div class="item">6間歇滾動</div> <div class="item">7間歇滾動</div> <div class="item">8間歇滾動</div> <div class="item">9間歇滾動</div> <div class="item">10間歇滾動</div> <div class="item">11間歇滾動</div> <div class="item">12間歇滾動</div> <div class="item">13間歇滾動</div> <div class="item">14間歇滾動</div> <div class="item">15間歇滾動</div> </div> </div> </body> </html>
注意點:
1.盒子塊要css 溢出隱藏:overflow:hidden
2.有兩個功能:間歇滾動/無縫滾動
3.先復制一塊一模一樣的代碼,無縫滾動:執行定時器一直增加scrollTop值,當scrollTop值大於盒子高度,在設置scrollTop為0,重新來過。間歇滾動在此基礎上加了setTimeout,間歇執行,在scrollTop到達指定的height停止
4.疑問:代碼中setInterval(function(){scrollIng()},30);這樣寫才可以執行,setInterval('scrollIng()',30);這樣就不行,有沒有大神指導下,兩者有啥區別?是啥機制?
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。