<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>图片左右滚动</title>
<style type="text/css">
#first{
width:820px;
height:160px;
overflow:hidden;
}
#second{
width:300%;
}
#second img{
float:left;
margin-right:3px;
width:160px;
height:160px;
border:#F00 1px solid;
}
#third{
float:left;
}
#four{
float:left;
background:#33F;
}
</style>
</head>
<body>
<a id="lef">向左</a>
<div id="first">
<div id="second">
<div id="third">
<img src="images/alefromeo.jpg" />
<img src="images/binli.jpg" />
<img src="images/frali.jpg" />
<img src="images/lamborghini.jpg" />
<img src="images/porsche.jpg" />
<img src="images/skoda.jpg" />
</div>
<div id="four"> </div>
</div>
</div>
<a id="right">向右</a>
<script type="text/javascript">
var first = document.getElementById("first");
var third = document.getElementById("third");
var four = document.getElementById("four");
var timer=null;
var direction="left";
four.innerHTML = third.innerHTML;//o verflow:hidden; //溢出的部分不显示
function leftScroll(){
//这个方法从上至下运行,不满足if条件,会先运行else里的内容。first.scrollLeft从0开始递增,一直到998
//假设递增到999时,会满足if条件,这时first.scrollLeft:999-998=1 又会接着进入else循环
//offsetLeft 为four块距离左屏幕的距离,而数值在变化的只有第四块,所有第三块的宽度是一直不变的
alert("aa"+ four.offsetLeft );//始终是998
alert("bb"+first.scrollLeft); //从0开始递增
if(four.offsetLeft<first.scrollLeft ){
first.scrollLeft-=four.offsetLeft;//998
}else{
first.scrollLeft++;
console.info(parseInt(first.scrollLeft));
}
}
timer = setInterval(leftScroll,2);//计时器
function rightScroll(){
if(first.scrollLeft<=0){
first.scrollLeft=four.offsetLeft;//998
}
else{
first.scrollLeft--;
}
}
document.getElementById("left").οnclick=function(){
direction="left";
clearInterval(timer);//清除计时器
timer = setInterval(leftScroll,1);
}
document.getElementById("right").οnclick=functio n(){
direction="right";
clearInterval(timer);
timer = setInterval(rightScroll,1);
}
first.onmouseover = function(){
clearInterval(timer);
}
first.onmouseout = function(){
if(direction=="left")
timer = setInterval(leftScroll,1);
else{
timer = setInterval(rightScroll,1);
}
}
</script>
</body>
</html>
js图片左右无缝滚动
最新推荐文章于 2022-02-18 19:52:16 发布