<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box{width: 200px;height: 200px;top: 300px;background-color: red;position: absolute}
#deadline{width: 1px;height: 900px;background-color: black;position: absolute;left: 1000px;}
</style>
<script>
window.onload = function(){
var BTN = document.getElementById("btn");
BTN.onclick = function(){
Starmove(1000);
}
}
var timer = null;
var Starmove = function(goal){
var BOX = document.getElementById("box");
var speed = (goal - BOX.offsetLeft)/18;
clearInterval(timer);
timer = setInterval(function(){
if(BOX.offsetLeft == goal ){
clearInterval(timer);
}else{
BOX.style.left = BOX.offsetLeft + speed + "px"
}
},30)
}
</script>
</head>
<body>
<button id="btn">开始运动</button>
<div id="box"></div>
<span id="deadline"></span>
</body>
</html>
上述代码中:两个问题:
1:当var speed = (goal - BOX.offsetLeft)/18;时,为什么box方块会出界?而只有设置var speed = (goal - BOX.offsetLeft)/8的时候不会出界?
2:我已经设置了
if(BOX.offsetLeft == goal ){
clearInterval(timer);
所以我认为无论我给speed设置一个怎样的数字,它都会最终停在目的地,为什么这个当我给speed = 5的时候它不会停止,而是无限运动出界?