javascript的setInterval实现图片滚动/图片轮播的效果

来源:互联网 发布:腾讯社会工程数据库 编辑:程序博客网 时间:2024/04/28 18:09

直接上代码,

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin: 0; padding: 0;}
#div0{width: 100%; height: 200px; border: 1px solid red; position: relative;}
#div1{width: 712px; height: 108px; margin: 50px auto; position: relative; overflow: hidden;}
#div1 ul{position: absolute;top: 0; left: 0;}
#div1 ul li{list-style: none; float: left;width: 178px;height: auto;}

</style>
<script type="text/javascript">
window.onload=function(){
var oDiv=document.getElementById('div1');
var oUl=oDiv.getElementsByTagName('ul')[0];
var aLi=oUl.getElementsByTagName('li');
var speed=-2;
var timer;
var aA=document.getElementsByTagName('a');
//尝试用cssText设置多个样式
aA[0].style.cssText="text-decoration:none;background: white; display: block; width: 40px; height: 80px; border: 1px solid black;border-radius: 20px; position: absolute; left: calc(10% - 10px); top: calc(30%); text-align: center; line-height: 80px; box-shadow: 1px 1px 2px #FF0000;";
aA[1].style.cssText="text-decoration:none;background: white; display: block; width: 40px; height: 80px; border: 1px solid black;border-radius: 20px; position: absolute; left: calc(90% + 10px); top: calc(30%);  text-align: center; line-height: 80px; box-shadow: 1px 1px 2px #FF0000;";

oUl.innerHTML=oUl.innerHTML+oUl.innerHTML;//可以在后面获取宽度看一下alert(oUl.offsetWidth);
oUl.style.width=aLi[0].offsetWidth*aLi.length+'px';//设置ul的宽度,用li的宽度*数量。



timer=setInterval(scroll,30);

oDiv.onmouseover=function(){
clearInterval(timer);
}
oDiv.onmouseout=function(){
timer=setInterval(scroll,30);
}

function scroll(){
if(oUl.offsetLeft<-oUl.offsetWidth/2)
{

//因为总长包含两组li,所以当一组已经滚完,即宽度正好到一半的时候,令ul的left=0,实现无限的效果
oUl.style.left=0;//或写成字符零oUl.style.left='0'。0后面可不跟px;
}

if(oUl.offsetLeft>0)//向左滚动时ul的left小于零,而向右时,left大于0
{
oUl.style.left=-oUl.offsetWidth/2+'px';
//这里,设为负值的含义就是把超过的一半挪到后面来,保证小于0的区域永远有li,制造出无限的效果
}

oUl.style.left=oUl.offsetLeft+speed+'px';
}

aA[0].onclick=function(){
speed=-2;
aA[0].style.backgroundColor='black';
aA[0].style.color='white';

//这里偷了个懒,点击未设置样式还原
}

aA[1].onclick=function(){
speed=2;
aA[1].style.backgroundColor='black';
aA[1].style.color='white';

}
}
</script>
</head>
<body>
<div id="div0">


<a href="javascript:;" >L</a>
<a href="javascript:;" >R</a>
<div id="div1">
<ul>
<li><img src="img/1.png"/></li>
<li><img src="img/1.png"/></li>
<li><img src="img/1.png"/></li>
<li><img src="img/1.png"/></li>
</ul>
</div>

</div>
</body>
</html>

原创粉丝点击