javascript - 无法使用 Javascript 为 div #box 设置动画

标签 javascript html animation

帮助!我不知道这里出了什么问题,我正在观看来自 Tuts+ 的教程视频。代码是准确的,但蓝色框没有向左移动。

当我在 moveBox 函数中放置一个警报时,我在控制台中看到警报一遍又一遍地触发相同的消息。

这是我的测试链接:

> Trying to animation a blue box left using Javascript <

这是视频的屏幕截图:

enter image description here

这是我的代码:

(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/

相关文章:

javascript - jQuery 动画颜色变化

html - CSS3 从左到右的过渡不起作用

javascript - IndexedDB:将文件存储为 File 或 Blob 或 ArrayBuffer。什么是最好的选择?

ios - 当 view1 帧触摸 view2 帧时停止动画

javascript - 压缩/缩小 AJAX 请求/响应中的 JSON

html - 包含图像映射的悬停元素在 Safari 中失去焦点?

Android实现从左向右滑动动画

javascript - 将 Owl Carousel 与 Ember 一起使用

javascript - CSS水平滚动?

javascript - 从 Dom 元素获取 CSS 路径