2017-03-02 91 views
1

我想從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

它不清楚你問還是什麼的問題是與此代碼。預期和目前發生了什麼? –

回答

0

在這種情況下,你可以使用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>