【问题标题】:Animation start as per CSS position动画根据 CSS 位置开始
【发布时间】:2017-03-02 13:12:39
【问题描述】:

我想在 javascript 中从 box 元素的默认位置开始动画。我已经在 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>

【问题讨论】:

  • 不清楚你在问什么或者这段代码有什么问题。预计会发生什么,目前会发生什么?

标签: javascript html css animation


【解决方案1】:

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

 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';
            }
        }
    };
#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>

【讨论】:

    猜你喜欢
    • 2021-11-07
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多