帮助!我不知道这里出了什么问题,我正在观看来自 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>
最佳答案
您在定位中拼错了“absolute”:
#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);
}());
关于javascript - 无法使用 Javascript 为 div #box 设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11939795/