帮助!我不知道这里出了什么问题,我正在关注来自Tuts +的教程视频。代码是准确的,但蓝框不是左边的动画。
当我在moveBox函数内部发出警报时,我在控制台中看到警报一遍又一遍地触发相同的消息。
以下是我的测试链接:
> Trying to animation a blue box left using Javascript <
以下是视频的屏幕截图:
这是我的代码:
(function() {
var speed = 10,
moveBox = function() {
var el = document.getElementById("box"),
i = 0,
left = el.offsetLeft,
moveBy = 3;
//console.log("moveBox executed " +(i+1)+ " times");
el.style.left = left + moveBy + "px";
if (left > 399) {
clearTimeout(timer);
}
};
var timer = setInterval(moveBox, speed);
}());
HTML:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>JavaScript 101 : Window Object</title>
<style>
#box {
position: abosolute;
height: 100px;
left: 50px;
top: 50px;
width: 100px;
background-color: Blue;
}
</style>
</head>
<body>
<div id="box"></div>
<script src="js/animation.js"></script>
答案 0 :(得分:2)
你在定位中误解了“绝对”:
#box {
position: absolute; // Your mispelling here
height: 100px;
left: 50px;
top: 50px;
width: 100px;
background-color: Blue;
}
一旦我解决了这个问题,它就运行良好。
建议 - 在这样的循环中放入第二个条件,这样如果动画由于某种原因失败,你就不会陷入无限循环。例如,您可能已经这样做了:
(function() {
var maxTimes = 1000;
var loopTimes = 0;
var speed = 10,
moveBox = function() {
var el = document.getElementById("box"),
i = 0,
left = el.offsetLeft,
moveBy = 3;
//console.log("moveBox executed " +(i+1)+ " times");
el.style.left = left + moveBy + "px";
loopTimes += 1;
if (left > 399 || loopTimes > maxTimes) {
clearTimeout(timer);
}
};
var timer = setInterval(moveBox, speed);
}());