2017-03-02 8 views
1

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>

関連する問題