js 实现图片无限横向滚动效果
门户网站好多都有产品无线滚动展现的效果:
测试demo1 -- 非无缝滚动(可以看出来从头开始的效果):
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代码如下:
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效果:
css代码如下:
.box{ width: 1000px; border: 1px solid #ccc; overflow: hidden; height: 110px; margin: 50px auto; white-space: nowrap; position: relative; } .con1,.con2{ display: inline; }
html结构同上;
js代码如下:
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); } }
我要成为酷酷的人http://www.cnblogs.com/CooLLYP/