1. 程式人生 > >js運動(定時器)

js運動(定時器)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>js定時器</title>
</head>
<body>
   
</body>
<script>

 var p = document.createElement('p');
 document.body.append(p)
 p.style.width="100px";
 p.style.height='100px'
 p.style.background="red";
 p.style.position="absolute";
 p.style.left='0';
 p.style.top='0';
 var speed = 1;
 var timer =setInterval(function () {
 	 speed+=1;
 	 p.style.left=parseInt(p.style.left)+speed+"px";
 	 p.style.top=parseInt(p.style.top)+speed+"px";
 	  if(parseInt(p.style.left)>200 && parseInt(p.style.top)>200){
          clearInterval(timer)//停止定時器
 	  }
 },30)

    
</script>
</html>