function tim(){
alert('定时器');
}
每隔2秒执行一次time函数(一直)
setInterval(tim,2000);
3秒后,执行一次time函数(一次)
setTimeout(tim,3000);
清除时间
clearInterval(tim);
获取属性值
var w=hd.style.width;
var m=hd.style.marginLeft;
alert(w);
width、margin-left必须为行内元素
定时跑
HTML
<input type="button" id="btn" value="点击"/>
<input type="button" id="stop" value="停止"/>
<br />
<div id="hd" style="position:absolute;left: 200px;"></div>
加了绝对定位之后定义left才能好用
css
*{
padding: 0;
margin: 0;
}
#btn{
margin-bottom: 50px;
}
#hd{
width: 200px;
height: 200px;
background-color: #DB7093;
}
var btn=document.getElementById('btn');
var hd=document.getElementById('hd');
var stop=document.getElementById('stop');
btn.onclick=function(){
// tim为全局变量
tim=setInterval(function(){
var old_left=hd.style.left;
// 获得当前的left值
var new_left=parseInt(old_left)+5;
// 计算新的left值,每次像素+5
hd.style.left=new_left+'px';
},20)
}
stop.onclick=function(){
clearInterval(tim);
}
tim=setInterval(function(){} 全局变量
var tim=setInterval(function(){} 仅在函数内
加速运动
var speed=1;
函数内加 speed=speed*1.05;
var new_left=parseInt(old_left)+speed;