您的位置:首页 > 编程语言 > Java开发

JavaScrip学习笔记(五)---定时器(一)实现图片无缝滚动

2016-06-04 22:11 756 查看
一、无缝滚动理论基础

基础知识

1.setInterval(function,time)、clearInterval(timer)

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。

clearInterval() 方法可取消由 setInterval() 设置的 timeout。

clearInterval() 方法的参数必须是由 setInterval() 返回的 ID 值。

2.offsetLeft与style.left的区别

offsetLeft与style.left的区别

二、代码片段

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>无缝滚动</title>
<style>
*{
margin: 0;
padding: 0;
}
#div2{
width: 400px;
margin: 100px auto;
}
input{
margin:0 auto;
text-align: center;
margin-left: 80px;
font-size: 40px;
}
#div1{
width: 712px;
height: 108px;
margin: 100px auto;
position: relative;
background-color: red;
overflow: hidden;
}
#div1 ul{
position: absolute;
left: 0;
top: 0;
}
#div1 ul li{
float: left;
width: 178px;
height: 108px;
list-style:none;
}
</style>
<script>
window.onload=function(){

var oDiv=document.getElementById('div1');
var oUl=document.getElementsByTagName('ul')[0];
var aLi=oUl.getElementsByTagName('li');
var lBtn=document.getElementById('lbtn');
var rBtn=document.getElementById('rbtn');

//将ul复制一份相加复制给ul(这样ul相当于有8张图片)
oUl.innerHTML=oUl.innerHTML+oUl.innerHTML;
oUl.style.width=aLi[0].offsetWidth*aLi.length+'px';

//speed控制图片移动方向和速度
var speed=2;

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);
}

//按钮控制移动方向
lBtn.onclick= function () {
speed=-2;
}
rBtn.onclick=function(){
speed=2;
}
};
</script>
</head>
<body>
<div id="div2" >
<input type="button" value="向左" id="lbtn"/>
<input type="button" value="向右" id="rbtn"/>
</div>

<div id="div1">
<ul>
<li><img src="images/1.jpg" alt=""/></li>
<li><img src="images/2.jpg" alt=""/></li>
<li><img src="images/3.jpg" alt=""/></li>
<li><img src="images/4.jpg" alt=""/></li>
</ul>
</div>

</body>
</html>


三、效果图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript