浅谈js的setInterval事件
setInterval()方法会不停地调用函数,直到clearInterval()被调用或窗口被关闭。由setInterval()返回的ID值可用作clearInterval()方法的参数。
setinterval()用法
setInterval(code,millisec[,"lang"])
后面就两个参数code是你的js代码,millisec为时间间隔,以毫秒计
<body>
<divid="content" style="position:relative;height:1000px;width:1000px;background-color:#666;">
<divid="one"style="position:absolute;top:0px;left:0px;height:100px;width:100px;background-color:red;"></div>
</div>
<script>
varone=document.getElementById('one')
varx=0;
vary=0;
varxs=10;
varys=10;
functionscroll(){
x+=xs;
y+=ys;
if(x>=document.getElementById('content').offsetWidth-one.offsetWidth-20||x<=0)
{
xs=-1*xs;
}
if(y>=document.getElementById('content').offsetHeight-one.offsetHeight-20||y<=0)
{
ys=-1*ys;
}
one.style.left=x;
one.style.top=y;
}
dt=setInterval(scroll,100);
one.onmouseover=function(){
clearInterval(dt);
};
one.onmouseout=function(){
dt=setInterval(scroll,100);
};
</script>
</body>
下面举一个简单的例子。
例1
functionshow(){trace("每隔一秒我就会显示一次");}
varsh;sh=setInterval(show,1000);
clearInterval(sh);
例2
<form>
<inputtype="text"id="clock"size="35"/>
<scriptlanguage=javascript>
varint=self.setInterval("clock()",50)
functionclock(){vart=newDate()
document.getElementById("clock").value=t
}
</script>
</form>
<divid="clock"></div>
<buttononclick="int=window.clearInterval(int)">Stopinterval</button>
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短