根据CSS位置动画开始

问题描述:

我想从box元素的默认位置开始在javascript中的动画。我已经在CSS中指定了所需的起始点,并且想让javascript到 获得该位置并开始相关动画。它从横轴上的0像素开始,但不是相对意义上的。我希望它是相对的,0代表没有变化。根据CSS位置动画开始

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

+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>