无缝滚动是项目中经常需要用到的一种特效,网上也有很多的示例代码,这里给大家分享的是一段比较简单实用的,而且兼容性也不错的代码,小伙伴们仔细研究下吧。
html 代码:
<</SPAN>html>
<</SPAN>head lang="en">
<</SPAN>meta charset="UTF-8">
<</SPAN>title>无缝滚动</</SPAN>title>
<</SPAN>script src="js/0010.js"></</SPAN>script>
<</SPAN>link rel="stylesheet" type="text/css" href="css/0010.css" />
</</SPAN>head>
<</SPAN>body>
<</SPAN>a href="javascript:">向左走</</SPAN>a>
<</SPAN>a href="javascript:">向右走</</SPAN>a>
<</SPAN>div id="div1">
<</SPAN>ul>
<</SPAN>li><</SPAN>img src="image/1.jpg"></</SPAN>li>
<</SPAN>li><</SPAN>img src="image/2.jpg"></</SPAN>li>
<</SPAN>li><</SPAN>img src="image/3.jpg"></</SPAN>li>
<</SPAN>li><</SPAN>img src="image/4.jpg"></</SPAN>li>
</</SPAN>ul>
</</SPAN>div>
</</SPAN>body>
</</SPAN>html>
CSS代码
*{
margin:0;
padding: 0;
}
#div1{
overflow: hidden;
background: blue;
position: relative;
width: 600px;
height: 150px;
margin:100px auto;
}
#div1 ul{
position: absolute;
left: 0px;
top: 0px;
list-style: none;
}
#div1 ul li{
float: left;
}
#div1 ul li img{
width:150px;
height:150px;
}
js:代码
window.onload=function(){
var oDiv=document.getElementById('div1');
var oUl=oDiv.getElementsByTagName('ul')[0];
var aLi=oUl.getElementsByTagName('li');
var timer=null;
var speed=2;//控制滚动速度以及方向
oUl.innerHTML=oUl.innerHTML+oUl.innerHTML;
oUl.style.width=aLi[0].offsetWidth*aLi.length+'px';
timer=setInterval(move,30);
oDiv.onmouseover=function(){//鼠标移入暂定
clearInterval(timer);
};
oDiv.onmouseout=function(){//鼠标移出继续滚动
timer=setInterval(move,30);
}
document.getElementsByTagName('a')[0].onclick=function(){
speed=-2;
}
document.getElementsByTagName('a')[1].onclick=function(){
speed=2;
}
function move(){//图片滚动
if(oUl.offsetLeft<-oUl.offsetWidth/2){
oUl.style.left=0;
}
if(oUl.offsetLeft>0){
oUl.style.left=-oUl.offsetWidth/2+'px';
}
oUl.style.left=oUl.offsetLeft+speed+'px';
}
}
效果是不是非常棒呢。