简单实现js间歇或无缝滚动效果

间歇、无缝滚动效果(用gif录制的效果不是很好,有兴趣的可以down代码),具体内容如下

简单实现js间歇或无缝滚动效果

代码:

<!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> <div> <div>1无缝滚动</div> <div>2无缝滚动</div> <div>3无缝滚动</div> <div>4无缝滚动</div> <div>5无缝滚动</div> <div>6无缝滚动</div> <div>7无缝滚动</div> <div>8无缝滚动</div> <div>9无缝滚动</div> <div>10无缝滚动</div> <div>11无缝滚动</div> <div>12无缝滚动</div> <div>13无缝滚动</div> <div>14无缝滚动</div> <div>15无缝滚动</div> </div> </div> <div> <div> <div>1间歇滚动</div> <div>2间歇滚动</div> <div>3间歇滚动</div> <div>4间歇滚动</div> <div>5间歇滚动</div> <div>6间歇滚动</div> <div>7间歇滚动</div> <div>8间歇滚动</div> <div>9间歇滚动</div> <div>10间歇滚动</div> <div>11间歇滚动</div> <div>12间歇滚动</div> <div>13间歇滚动</div> <div>14间歇滚动</div> <div>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);这样就不行,有没有大神指导下,两者有啥区别?是啥机制?

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzsgpz.html