简体   繁体   中英

Moving a div left and right continously

I've been trying to get this javascript animation to work for hours now, and 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
  });
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM