I've been trying to get this javascript animation to work for hours now, an开发者_运维问答d I got nothing. The problem isn't getting my div box to move from left to right(or from top to bottom), it's the opposite of each case that I have trouble with it. Here's what I have so far(In addition, I have set boundaries set to keep my moving box contained within the view window so if it hits any one of sides, it should move to the opposite direction). Any help is awesome at this point.
Note: the next step is to create a bouncing effect for the box, but i'll worry about that once i get simple animation working.
setInterval(function(){
if(parseInt(box.style.left) > parseInt(viewDim.width - 57)){
box.style.left -= parseInt(box.style.left) - 2 + 'px';
/* } else if(parseInt(box.style.left) < 0){
//debug_log("HIT!!");
//parseInt(box.style.left) += 2 + 'px';
} else if(parseInt(box.style.top) > parseInt(viewDim.height-58)){
} else if(parseInt(box.style.top) < 0){*/
} else {
box.style.left = parseInt(box.style.left) + 2 + 'px';
//box.style.top = parseInt(box.style.top) + 5 + 'px';
}
}, 20);
Code like this always works for me:
var boxWidth = 57, delta = 2;
setInterval(function(){
var left = parseInt(box.style.left);
if(left >= parseInt(viewDim.width - boxWidth)){
delta = -2;
}
if (left <= 0) {
delta = 2;
}
box.style.left = left + delta + 'px';
}, 20);
Although you have your solution now, I couldn't help myself from making complete code here.
The bouncing box bounces around inside the parent element. Tested in IE8, FF3, and Opera11.
This can give an idea, how to do it with jQuery
http://jsfiddle.net/rFkpy/
$('#myDiv').click(function() {
$(this).animate({
left: '+=250'
}, 1500, "easeOutBounce", function() {
// callBack
});
});
精彩评论