javascript中的setIntervar()函数无限的隔一段时间执行,利用这个原理可以实现一个图片无缝滚动的功能,当然现在网上已经有很多这方面的功能,但是自己动手来实现的还是有点不一样的,不多说什么了,直接上代码,当然这个功能还可以扩展,以后有时间一定要扩展下!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
*{margin:0;padding:0;}
#div1{width:956px; height:190px; background-color:#FFFFCD; margin:50px auto; position:relative; overflow:hidden;}
#div1 ul{position:absolute; left:0; top 0; }
#div1 ul li{float:left; list-style:none; width:239px; height:190px;}
</style>
<script>
window.onload=function(){
var oDiv = document.getElementById('div1');
var oUl = document.getElementsByTagName('ul')[0];
var oLis = document.getElementsByTagName('li');
var oBtn1 = document.getElementById('btn1');
var oBtn2 = document.getElementById('btn2');
var oBtn3 = document.getElementById('btn3');
var oBtn4 = document.getElementById('btn4');
var timer = null;
var speed = 2;
oUl.innerHTML += oUl.innerHTML;
oUl.style.width = oLis[0].offsetWidth*oLis.length+'px';
function move(){
timer = setInterval(function(){
if(oUl.offsetLeft < -oDiv.offsetWidth){
oUl.style.left = 0;
}
if(oUl.offsetLeft > 0){
oUl.style.left = -oDiv.offsetWidth+'px';
}
oUl.style.left = oUl.offsetLeft+speed+'px';
},30);
}
oBtn1.onclick=oDiv.onmouseout = function(){
move();
}
oBtn2.onclick=oDiv.onmouseover= function(){
clearInterval(timer);
}
oBtn3.onclick = oBtn4.onclick = function(){
speed = -speed;
}
//移动
move();
}
</script>
</head>
<body>
<input type="button" id="btn1" value="开始">
<input type="button" id="btn2" value="结束">
<input type="button" id="btn3" value="向左移">
<input type="button" id="btn4" value="向右移">
<div id="div1">
<ul>
<li><img src="../img/1.png"></li>
<li><img src="../img/2.png"></li>
<li><img src="../img/3.png"></li>
<li><img src="../img/4.png"></li>
</ul>
</div>
</body>
</html>
图片先上传一张吧,其实都差不多。
PS:发现JS真是越来越强大了,越来越喜欢JS了,以后一定要深入研究!