<style type="text/css">
#div1{
width:300px;
height:300px;
background:red;
position:absolute;
left:0px;
}
</style>
<script type="text/javascript">
window.onload=function(){
//获取Box1
var button1=document.getElementById("move");
// 获取 btn01
var div1=document.getElementById("div1");
var button2=document.getElementById("move2");
button1.onclick=function(){
move(div1,800,10);
};
button2.onclick=function(){
move(div1,0,10);
};
};
var timer;
function move(obj,target,speed){
clearInterval(timer);
var current=parseInt(getStyle(obj,"left"));
if(current>target){
speed=-speed;
}
timer=setInterval(function(){
var oldleft=parseInt(getStyle(obj,"left"));
var newleft=oldleft+speed;
if((speed>0&&target<newleft)||(speed<0&&target>newleft)){
newleft=target;
}
obj.style.left=newleft+"px";
if(newleft==target){
clearInterval(timer);
}
},30);
}
//定义一个函数,用来获取指定元素当前的样式
//参数 :
//obj 表示的是要获取样式的元素
//name 表示的是要获取元素的样式名
function getStyle(obj,name){
if(window.getComputedStyle){
//正常浏览器的方式,具有getComputedStyle()的方法
return getComputedStyle(obj,null)[name];
}else{
//IE8 的方式,没有getComputedStyle()的方法
return obj.currentStyle[name];
}
};
</script>
</head>
<body>
<button id="move">请给我向右移动</button>
<button id="move2">请给我向左移动</button>
<br/><br/>
<div id="div1"></div>
</body>
运行结果图: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200923213551897.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3lyaGx5eW91a25vdw==,size_16,color_FFFFFF,t_70#pic_center)
定时器学习二
最新推荐文章于 2024-09-09 09:35:48 发布
本文主要探讨JavaScript中的定时器机制,结合示例图深入解析其工作原理和常见应用场景。
摘要由CSDN通过智能技术生成