开发者

JQuery If condition (specific for a content slider)

I am new at JQuery and I have a specific question about the IF-THEN-ELSE fork. The big problem for me is the syntax of t开发者_StackOverflow中文版his (I suck at Javascript). It would help me if anyone can "translate" the pseudo code into a JQuery (or Javascript) valide code.

The pseudo code:

IF "#Contentshowroom" css "left" is NOT > 1960px

THEN On Click "#Forwardbutton" DO animate "#Contentshowroom" css "left" =+980px

ELSE You can not click on the "#Forwardbutton"


Place the if() statement in the click handler for #Forwardbutton to test the left position of #Contentshowroom.

If you're using jQuery:

$('#Forwardbutton').click(function() {
    var $Content = $('#Contentshowroom');
    if( $Content.offset().left <= 1960 ) {
        $Content.animate({ left: '+= 980' });
    }
});

So now when you click the Forwardbutton, it will check the left .offset() position of the Contentshowroom to see if it is less than or equal to 1960px. And if so, it will animate the left position an additional 980px.

jQuery's .offset() method gives you the top/left positions relative to the body. If you want it relative to its parent container, then use jQuery's .position() method.


click doc
animate doc
offset doc

$("#Forwardbutton").click( function( e ){

   // lookup is safe, no noticable performance cost.
   // though a reference makes it more losely coupled.
   // I'll leave it at your discretion.
   var target = $("#Contentshowroom")
   // NOTE: the offset parent should have position relative or absolute.
   , leftPos = target.offset().left; 

   if ( leftPos < 1960 ) {

      target.animate({
         left : leftPos + 980
      }); // see docs to tweak animation

   } // else do nothing.

} );

Could also use e.preventDefault(); , but don't if it's not needed, it will safe you headaches if you add more listeners to your buttons and find out they're not working.


// first store contentShowroom and it's left property to save getting > 1
var contentShowroom = $('#Contentshowroom');
var showroomLeft = contentShowroom.css('left');
var forwardButton = $('#Forwardbutton');

if (showroomLeft <= 1960){
  forwardButton.click(function(){
    contentShowroom.animate({left: showroomLeft + 980);
  }
}
else {
  forwardButton.unbind('click');
}


if this is to be run once at the beginning then

if ( $('#Contentshowroom').offset().left > 1960 )
{
  $('#Forwardbutton').click( function(){
    $('#Contentshowroom').animate({left:'+=980'});
  } );
}
else
{
  // if the #Contentshowroom is a link then 
  $('#Contentshowroom').removeAttr('href');
  // if the #Contentshowroom is a button then 
  // $('#Contentshowroom').attr('disabled',true);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜