动画从CSS位置开始

时间:2017-03-02 13:12:39

标签: javascript html css animation

我想从box元素的默认位置开始使用javascript动画。我已经在CSS中指定了所需的起点,并希望使用javascript 得到那个位置并开始与之相关的动画。它从水平轴上的0像素开始,但不是相对意义上的。我希望它是相对的,其中0应该意味着没有变化。



//calling the function in window.onload to make sure the HTML is loaded
window.onload = function() {
     var pos = 0; 
    //our box element
    var box = document.getElementById('box');
    var time = setInterval(move, 10);

    function move() {
        if(pos >= 150) {
            clearInterval(time);
        }
        else {
            pos += 1;
            box.style.left = pos+'px';
        }
    }
};

#container {
    width: 200px;
    height: 200px;
    background: green;
    position: relative;
}
#box {
    width: 50px;
    height: 50px;
    background: red;
    position: absolute;
    left: 50px;
    top: 50px;
}

<div id="container">
    <div id="box"> </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

在这种情况下,您可以使用computedStyle:

&#13;
&#13;
 window.onload = function ()
    {
        var pos = 0;
        //our box element
        var box = document.getElementById('box');
        var time = setInterval(move, 10);

        function move()
        {
            var computedStyle = window.getComputedStyle(box);
            var pos = computedStyle.left;
            if (pos == '150px')
            {
                clearInterval(time);
            }
            else
            {
                var posValue = parseInt(pos.slice(0, pos.length - 2));
                posValue += 1;
                box.style.left = posValue + 'px';
            }
        }
    };
&#13;
#container {
            width: 200px;
            height: 200px;
            background: green;
            position: relative;
        }

        #box {
            width: 50px;
            height: 50px;
            background: red;
            position: absolute;
            left: 50px;
            top: 50px;
        }
&#13;
<div id="container">
          <div id="box"> </div>  
        </div>
&#13;
&#13;
&#13;