网络编程
位置:首页>> 网络编程>> JavaScript>> javascript定时器的简单应用示例【控制方块移动】

javascript定时器的简单应用示例【控制方块移动】

作者:longzhoufeng  发布时间:2024-07-05 11:00:33 

标签:javascript,定时器

本文实例讲述了javascript定时器的简单应用。分享给大家供大家参考,具体如下:


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>www.aspxhome.com 定时器的应用</title>
 <style>
   #Div1 { width: 100px; height: 100px; position: absolute; background-color: red; top: 50px; }
 </style>
</head>
<body>
<input id="oBtn1" type="button" value="铵钮">
<div id="Div1"></div>
<script>
 var oBtn = document.getElementById("oBtn1");
 var oDiv = document.getElementById("Div1");
 //var timer=null;
 //oDiv.timer=null;
 oBtn.onclick = function() {
   clearInterval(oDiv.timer)
   oDiv.timer = setInterval(function() {
     var speed = parseInt(getStyle(oDiv, "left")) + 9;
     if(speed > 800) {
       speed = 800;
     }
     oDiv.style.left = speed + "px"
     if(speed == 800) {
       clearInterval(oDiv.timer);
       //alert(speed)
     }
   }, 50)
 }
 function getStyle(obj, attr) {
   return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr]
 }
</script>
</body>
</html>

运行结果:

javascript定时器的简单应用示例【控制方块移动】

希望本文所述对大家JavaScript程序设计有所帮助。

来源:https://blog.csdn.net/longzhoufeng/article/details/72825611

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com