2015.7.11js-10(无缝滚动)
1.实现原理:setInterval定时器,让某元素position的left属性定时滚动,使用到js中的元素的offsetLeft属性。
2.案例:1.css的实现是外div是4张图片的总宽度,设置relative然后overflow隐藏。子代有ul层设置为absolute;left属性移动时都是移动整个ul层的。;
2.4张图片无缝滚动,再复制4张(1,2,3,4)在第4张后面,li下有4张图片,获取li的offsetWidth(),然后算出ul的总宽度,当包着4张图片的ul层的offsetLeft滚动到一半的时候,将前4张的left变成0,这样滚动的时候就会无缝滚动了。设置ul层的offsetLeft来控制滚动。
3.demo地址:http://www.alanjs.comeze.com/study/demo11setInterval.html
<script type="text/javascript"> window.onload = function(){ var slide = document.getElementById("slideImg"); var moveUl = document.getElementById("moveUl"); var aLi = slide.getElementsByTagName("li"); var timer = null; var speed = -2; var prev = document.getElementById("prev"); var next = document.getElementById("next"); moveUl.innerHTML = moveUl.innerHTML + moveUl.innerHTML; //先复制4张图片放在后面 moveUl.style.width = aLi[0].offsetWidth*aLi.length + "px"; //获取一个li的宽度来设置ul层的总宽度 timer = setInterval(move,30) slide.onmouseover = function(){ if(timer){ clearInterval(timer); } } slide.onmouseout = function(){ timer = setInterval(move,30); } prev.onclick = function(){ speed = -2; } next .onclick = function(){ speed = 2; } function move(){ if(moveUl.offsetLeft < -moveUl.offsetWidth/2){ //向左滚动,当滚动到一半的时候,前面4张就跳到后面 moveUl.style.left = "0"; } if(moveUl.offsetLeft > 0){ moveUl.style.left = -moveUl.offsetWidth/2 + "px"; //向右滚动,当一开始滚动的时候,ul的left属性大于0,后面4张就立即跳到前面
}
moveUl.style.left = moveUl.offsetLeft+speed + "px"; //设置ul层的offsetLeft来控制滚动
}
}
</script>
<style> #wrap{width:1603px;margin:0 auto;height:300px;} #sliderImg{width:1308px;height:203px;position:relative;overflow:hidden;border:1px solid red;} #sliderImg ul{positin:absolute;left:0px;top:0px;} #sliderImg ul li{list-style:none;float:left} </style> <body> <div id="wrap"> <div id="sliderImg"> <ul id="moveUl"> <li><a href="javascript:;"><img src="images/slide5.jpg" /></a></li> <li><a href="javascript:;"><img src="images/slide6.jpg" /></a></li> <li><a href="javascript:;"><img src="images/slide7.jpg" /></a></li> <li><a href="javascript:;"><img src="images/slide8.jpg" /></a></li> </ul> </div> <a id="prev" href="javascript:;">prev</a> <a id="next" href="javascript:;">next</a> </div> </body>