2015-11-05 19 views
1

我想簡單地每x毫秒設置一次形狀的動畫。我在CODEPEN中這樣做。無法在codepen中爲DOM元素設置動畫

我試圖移動它使用:

的JavaScript:

  • ball.getBoundingClientRect().left += 100 + 'px'

  • ball.style.left += 100 + 'px'

的jQuery:

  • $('#ball').position().left += 100 + 'px'

但似乎沒有任何工作。球出現,但不動。超時也被稱爲。在控制檯中沒有錯誤被拋出。

var ball = null; 
var ball_x = null; 
var ball_y = null; 

function doMove() { 
    ball.style.left += 100 + 'px'; 
    setTimeout(doMove,100); 
} 

function init() { 
    ball = document.getElementById('ball'); 
    ball_x = ball.getBoundingClientRect().left; //displays correct location 
    ball_y = ball.getBoundingClientRect().top; //displays correct location 

    doMove(); 
} 

window.onload = init; 

CSS:

#ball { 
    width: 25px; 
    height: 25px; 
    background-color: red; 
    border-radius: 50%; 
    position: absolute; 
    left: 100px; 
    top: 200px; 
} 

HTML:

<div> 
    <div id='ball'></div> 
</div> 
+0

凡* codepen *網址是什麼? – Rayon

+0

@RayonDabre見上面 – Growler

+0

'getBoundingClientRect()'是隻讀屬性.. – Rayon

回答

3

問題是left CSS返回文本就像100px值不是一個算一個,這樣是行不通的。因此,使用+=與它字符串連接不是數字域創建一個無效的值

getBoundingClientRect()返回一個只讀的對象,所以改變其屬性沒有效果

返回的值是一個DOMRect對象,其中包含只讀左側, 頂部,右側和底部屬性,以像素爲單位描述邊框。頂部和左側的 相對於視口的左上角。

var ball = null; 
 

 
function doMove() { 
 
    ball.style.left = ((parseInt(ball.style.left) || 0) + 100) + 'px' 
 
    setTimeout(doMove, 2000); 
 
} 
 

 
function init() { 
 
    ball = document.getElementById('ball'); 
 

 
    doMove(); 
 
} 
 

 
window.onload = init;
#ball { 
 
    width: 25px; 
 
    height: 25px; 
 
    background-color: red; 
 
    border-radius: 50%; 
 
    position: absolute; 
 
    left: 100px; 
 
    top: 200px; 
 
    transition: left 2s; 
 
}
<div> 
 
    <div id='ball'></div> 
 
</div>

+0

如此快速準確! #尊重 – Rayon