0

I have a few functions bellow that slides a div left and right. It works perfectly, except for the fact that I need it to stop once the user reaches the end of the div. IE: the left arrow should move no further than left: 0;. Any help with this would be appreciated!

$(".left-arrow").mouseover(function(){
  playanim("+=30px");
}).mouseleave(function(){
  stopanim();
}); 

$(".right-arrow").mouseover(function(){
  playanim("-=30px");
}).mouseleave(function(){
  stopanim();
}); 

function playanim(speed) {
  // launch the anim with the desired side
  $("#slides").animate({ 
    left: speed,
  }, 1000,'linear',function(){playanim(speed);});
}

function stopanim() {
  // stop the animation and clear the animation queue
  $("#slides").stop(true);
}
4

2 回答 2

3

You can check left position using position or Offset.

Solution using position:

function playanim(speed) {

  var position = $("#slides").position();

  //if position (or offset, if you like) is more than 0, we may move.
  if ( position.left > 0 ) {
     // make sure you don't accidentally go more left than 0
     if( position.left < 30) {
        speed = 30 - position.left;
     }
     // launch the animation with the desired side
     $("#slides").animate({ 
        left: speed,
     }, 1000,'linear',function(){playanim(speed);});
   }
}
于 2013-11-12T04:39:19.400 回答
0

You just need to add a while statement and before the while statement use the position method of jquery to get the position of the element.

While(position!={left:0}) // Or something like that
{
    //then move
}

You can find the reference for position here http://api.jquery.com/position/

于 2013-11-12T04:11:23.917 回答