2015-11-05 51 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