大家肯定在网页上见过无缝滚动的画面,鼠标点上去后滚动会停止放开后继续滚动,现在给大家介绍一下要实现的功能代码。
下方代码为网页开头及样式:
<!DOCTYPE html>
<html>
<head>
<title>定时器2</title>
<style>
* {margin:0;padding:0;}
#div1 {width:1200px; height:100px; margin:100px auto;position: relative;
background: red; overflow: hidden;}
#div1 ul {position: absolute;left:0;top:0;}
#div1 ul li {float:left; width:300px;height:100px;list-style: none;}
</style>
下方代码为js代码写法:
<script type="text/javascript">
window.onload=function()
{ var speed=2;
//通过id选中要操作的div
var oDiv=document.getElementById('div1');
var oUl=oDiv.getElementsByTagName('ul')[0];
var aLi=oUl.getElementsByTagName('li');
oUl.innerHTML=oUl.innerHTML+oUl.innerHTML;
oUl.style.width=aLi[0].offsetWidth*aLi.length+'px';
function move(){
if(oUl.offsetLeft<-oUl.offsetWidth/2)
{
oUl.style.left='0';
}
if(oUl.offsetLeft>0)
{
oUl.style.left=-oUl.offsetWidth/2+'px';
}
oUl.style.left=oUl.offsetLeft+speed+'px';
}
//设置时间选择器
var timer=setInterval(
move,30);
//鼠标放上后清空选择器
oDiv.onmouseover=function(){
clearInterval(timer);
};
//鼠标移开后打开时间选择器
oDiv.onmouseout=function(){
timer=setInterval(move,30);
}
//设置往左移动
document.getElementsByTagName('a')[0].onclick=function()
{
speed=-2;
};
//设置往右移动
document.getElementsByTagName('a')[1].onclick=function()
{
speed=2;
};
};
</script>
</head>
下方为页面结束:
<body>
<a href="javascript:;">向左走</a>
<a href="javascript:;">向右走</a>
<div id="div1">
<ul>
<li><img src="img2/1.jpg"/></li>
<li><img src="img2/2.jpg"/></li>
<li><img src="img2/3.jpg"/></li>
<li><img src="img2/4.jpg"/></li>
</ul>
</div>
</body>
</html>
由于页面为滚动页面,截图不能直观看到效果,所以请大家自行制作一个。