I want to simply animate a shape every x milliseconds. I'm doing this in CODEPEN .
I tried moving it using:
JavaScript:
ball.getBoundingClientRect().left += 100 + 'px'
ball.style.left += 100 + 'px'
jQuery:
$('#ball').position().left += 100 + 'px'
But nothing seemed to work. The ball appears, but does not move. The timeout is being called as well. No errors in console are being thrown.
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>
The problem is left
css returns a text like 100px
value not a numerical one so that won't work. So using +=
with it does a string concatenation not a numeric one creating a invalid value
getBoundingClientRect() returns a read-only object, so changing its properties don't have an effect
The returned value is a DOMRect object, which contains read-only left, top, right and bottom properties describing the border-box in pixels. top and left are relative to the top-left of the viewport.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.