JavaScript 里有定时器 setInterval(fun,time) / clearInterval() ; 延时器 setTimeout(fun,time) / clearTimeout()。 区别在于,前者可以每隔一定时间执行函数,而后者一般只能执行一次函数。在工程里,一般用前者多一点。这里给大家来举两个个小例子:
1 定时器实现页面的计时操作:
1.1 JS 代码:
<script type="text/javascript">
window.onload=function(){
var count=0
var c=document.getElementById("count");
var timer=setInterval(function(){
c.innerHTML=count++;
if(count==11){
clearInterval(timer);
c.innerHTML="";
}
},1000);
};
</script>
1.2 HTML 代码:
<div id="count"></div>
2 使用JS 定时器实现 滑块移动:
2.1 JS代码:
<script type="text/javascript">
window.onload=function(){
var box=document.getElementById("box");
var box1=document.getElementById("box1");
var btn=document.getElementById("btn");
var btn1=document.getElementById("btn1");
var btn2=document.getElementById("btn2");
btn.onclick=function(){
move(box,"top",1000,20);
}
btn1.onclick=function(){
move(box1,"left",1000,10);
}
btn2.onclick=function(){
move(box1,"width",800,20,function(){
move(box1,"height",400,20);
});
}
//可以根据 target 参数进行判断 向哪个方向移动
function move(obj,attr,target,speed,callback){
var current=parseInt(getStyle(obj,attr));
//alert(current);
//根据目标的位置来判定 speed的值是正是负
if(current>target){
speed=-speed;
}
//自定义对象定时器 防止对象之间的混乱操作
clearInterval(obj.timer);
//alert(oldValue);
obj.timer=setInterval(function(){
var oldValue=parseInt(getStyle(obj,attr));
var newVal=oldValue+speed;
//如果移动的越界 进行重置
if((speed<0 && newVal<=target) || (speed>0 && newVal>=target)){
newVal=target;
}
obj.style[attr]=newVal+"px";//注意这里的是 [] 不是用的 style.attr 因为这里 attr 为变量
if(newVal==target){
clearInterval(obj.timer);
callback && callback();//回掉函数 先判断 有就执行 没有不执行
}
},30);
}
}
//obj:获取样式元素
//name:获取样式名
function getStyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{
return obj.currentStyle[name];
}
}
</script>
2.2 HTML 代码:
<button id="btn">点击可以上下移动</button>
<button id="btn1">点就可以左右移动</button>
<button id="btn2">测试</button>
<br><br><br>
<div id="box"></div>
<div id="box1"></div>
2.3 CSS代码:
<style type="text/css">
#box{
width:100px;
height:100px;
background-color:red;
position:absolute;
left:0px;
}
#box1{
width:100px;
height:100px;
background-color:red;
position:absolute;
left:0px;
top:200px;
}
</style>
以上带代码大家可以测试下,挺有趣的。