js 图片无缝滚动

时间:2023-03-09 13:36:49
js 图片无缝滚动

html部分

<div id="roll">
<a href="javascript:void(0)" class="prev">向左</a>
<a href="javascript:void(0)" class="next">向右</a>
<div id="scroll">
<ul>
<li><img src="img/5.jpg"/></li>
<li><img src="img/6.jpg"/></li>
<li><img src="img/7.jpg"/></li>
</ul>
</div>
</div>

css部分

ul,
ul li{
list-style: none;
margin:0 ;
padding:0 ;
}
ul:after{
clear: both;
display: block;
content: " ";
visibility: hidden;
}
#scroll{
width:1290px ;
height: 195px;
margin:0 auto;
overflow: hidden;
position: relative;
}
#scroll ul {
position: absolute;
left: 0;

}
#scroll ul li{
float:left;
}
a{
position: absolute;
z-index: 99;
}
.prev{
top:80px;
left:26px;
}
.next{
top:80px;
right:26px;
}

js部分

function getId(id){
return document.getElementById(id);
};
window.onload=function(){
var scroll=getId('scroll');
var ulList=scroll.getElementsByTagName('ul')[0];
ulList.innerHTML+=ulList.innerHTML;
var ulListLi=ulList.getElementsByTagName('li');
ulList.style.width=ulListLi[0].offsetWidth*ulListLi.length+'px';//设置ul的宽
var speed=-5;
var timer=null;
function roll(){ //滚动函数
ulList.style.left=ulList.offsetLeft+speed+'px';
if(ulList.offsetLeft < -ulList.offsetWidth/2){
ulList.style.left='0px';
}else if(ulList.offsetLeft >0){

ulList.style.left=-ulList.offsetWidth/2+'px';

}
}

timer=setInterval(roll,50)

//按钮点击事件
var prev=document.getElementsByClassName('prev')[0];
var next=document.getElementsByClassName('next')[0];
prev.onclick=function(){
speed=-5;
}
next.onclick=function(){
speed=5;
}

//ul区域移入移出区域事件

ulList.onmouseenter=function(){
clearInterval(timer);
}
ulList.onmouseleave=function(){
timer=setInterval(roll,50)
}

}