一.要实现的效果
1.点击按钮实现左右滚动
2.鼠标放上去实现清除定时器
二.效果图片
三.代码
1.css
<style type="text/css">
#div1{
margin:50px;
width:800px;
height:200px;
background:pink;
position:relative;
overflow:hidden;
}
#div1 ul{
border:solid 1px #ccc;
margin-top:20px;
width:800px;
height:150px;
position:absolute;
float:left;
}
#div1 ul li{
list-style:none;
float:left;
width:200px;
height:150px;
}
#div1 ul li img{
float:left;
margin-left:0px;
width:200px;
height:150px;
}
a{text-decoration: none;}
</style>
2.html
<a href="#" id="left">向左滚</a>
<a href="#" id="right">向右滚</a>
<div id="div1">
<ul>
<li><img src="img/2.png"></li>
<li><img src="img/1.png"></li>
<li><img src="img/3.png"></li>
<li><img src="img/4.png"></li>
</ul>
</div>
3.js
<script type="text/javascript">
var oDiv1=document.getElementById("div1");
var oUl=oDiv1.getElementsByTagName("ul")[0];
var lis=oUl.getElementsByTagName("li");
oUl.innerHTML+=oUl.innerHTML; //将图片拷贝一份用于轮播
//ul的宽度等于
oUl.style.width=lis[0].offsetWidth*lis.length+'px';
var speed=2;
var oA1=document.getElementById("left");
var oA2=document.getElementById("right");
//左滚
oA1.onclick=function(){
speed=-2;
}
//右滚
oA2.onclick=function(){
speed=+2;
}
//移动函数
function move(){
//左移(即oUl.offsetLeft-2) 当图片往左边移动到一半的时候重新UL左边距设置为0
if(oUl.offsetLeft<-oUl.offsetWidth/2){
oUl.style.left=0;
}
//右移(即oUl.offsetLeft+2) 如果图片往右边移动到超出左边的边界时将UL重新挪到左边来
if(oUl.offsetLeft>0){
oUl.style.left=-oUl.offsetWidth/2;
}
oUl.style.left=oUl.offsetLeft+speed+'px';
}
var timer=setInterval(move,30);
//当鼠标移入UL的时候关闭定时器
oUl.onmouseover=function(){
clearInterval(timer);
}
oUl.onmouseout=function(){
timer=setInterval(move,30);
}
</script>