无缝滚动
HTML
<div id="outer"> <div id="inner"> <div id="demo1"></div> <div id="demo2"></div> </div> </div> <input type="button" name="" id="" value="向左" /> <input type="button" name="" id="" value="向右" />
CSS
*{ margin: 0; padding: 0; } img{ width: 500px; height: 310px; float: left; } #outer{ margin: 50px auto; width: 500px; height: 310px; border: 1px solid #000; overflow: hidden; } #inner{ width: 6000px; height: 310px; } #inner div{ float: left; }
JS
var imgArray=["https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511167162133&di=fe27f741ca0c915199d4576a8ffac946&imgtype=0&src=http%3A%2F%2Fwww.ywga.gov.cn%2Fjwgk%2Fsyzc%2F201703%2FW020170331331041430290.jpg", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511166484577&di=f000cde0483941d947a1628cc91b1c49&imgtype=0&src=http%3A%2F%2Fimg18.3lian.com%2Fd%2Ffile%2F201706%2F05%2F962ba7f592396f12cab97a9490031671.jpg", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511167245165&di=b67c232671c9018f44c7bd2c158dc0a5&imgtype=0&src=http%3A%2F%2Fuploads.xuexila.com%2Fallimg%2F1703%2F1017-1F302110K6.jpg", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511167262450&di=defa4f8b1f2cf03229473b93bd0b4713&imgtype=0&src=http%3A%2F%2Fww2.sinaimg.cn%2Flarge%2Fd75e3906jw1eiwxjge3zxj20t50iggqq.jpg", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511167297748&di=5303510e2607fd41f607236ce043e475&imgtype=0&src=http%3A%2F%2Fimg2.zol.com.cn%2Fproduct%2F104%2F642%2FceqOwlYvIkPSk.jpg", "https://timgsa.baidu.com/timg?image&quality=80&size=b10000_10000&sec=1511157232&di=1c3c867d3eb753a7a098304afc0ed891&src=http://rescdn.qqmail.com/dyimg/20140807/74DA11875739.jpg" ]; var len=imgArray.length; var dOuter=document.getElementById("outer"); var demo1=document.getElementById("demo1"); var demo2=document.getElementById("demo2"); var btn=document.getElementsByTagName("input"); var timer=null; //页面初始化 for (var i=0;i<len;i++) { demo1.innerHTML+="<img src='"+imgArray[i]+"' />"; } demo2.innerHTML=demo1.innerHTML; dOuter.onOff=true; //鼠标移入 dOuter.onmouseover=function(){ clearInterval(timer); } //鼠标移出 dOuter.onmouseout=function(){ if(this.onOff){ clock(); }else{ clock2(); } } //鼠标点击按钮切换不同的运动方式 //向左运动 btn[0].onclick=function(){ dOuter.onOff=true; clock(); } btn[1].onclick=function(){ dOuter.onOff=false; clock2(); } setTimeout(clock,1500); //向左运动 function clock(){ clearInterval(timer); timer=setInterval(moveLft,10); } //向右运动 function clock2(){ clearInterval(timer); timer=setInterval(moveRight,10); } //向左运动 function moveLft(){ //容器向左滚动的距离 dOuter.scrollLeft+=2; //判断临界值 if(dOuter.scrollLeft>=demo1.offsetWidth){ dOuter.scrollLeft=0; } //每一幅图停顿一次 if(dOuter.scrollLeft%500==0){ clearInterval(timer); timer=setTimeout(clock,1500); } } //向右运动 function moveRight(){ dOuter.scrollLeft-=2; if(dOuter.scrollLeft<=0){ dOuter.scrollLeft=demo1.offsetWidth; } if(dOuter.scrollLeft%500==0){ clearInterval(timer); timer=setTimeout(clock2,1500) } }