1

我是JQuery的新手,我有關於IF-THEN-ELSE分支的具體問題。 對我來說,最大的問題是這個的語法(我吮吸Javascript)。如果任何人都可以將僞代碼「翻譯」爲JQuery(或Javascript)的代碼,它會幫助我。JQuery如果條件(特定於內容滑塊)

的僞代碼:

IF 「#Contentshowroom」 CSS 「左」 是不是> 1960px

THEN 點擊 「#Forwardbutton」 DO 動畫 「#Contentshowroom」 CSS「左」 = + 980px

ELSE不能點擊 「#Forwardbutton」

回答

1

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. 

}); 

也可以使用e.preventDefault();,但不,如果不需要的話,它會安全,你的頭痛,如果你添加更多的聽衆到您的按鈕,並找出他們'不工作。

+0

我認爲,關於不使用'的.css()您的筆記'是正確的。如果'left'沒有使用CSS設置,那麼您可能會獲得'auto'而不是位置,您的雙位NOT運算符將轉換爲'0'。 – user113716 2010-11-04 11:13:48

+0

這對我有用!謝謝BGerrissen。 :) – Tomkay 2010-11-04 11:16:40

+0

@patrick偏移()更好,在後臺更少,所以完全改變它。 BITWISE NOT實際上很好用,如果你在沒有框架的情況下編寫低級別的javascript,但是使用了jQuery,所以我最好不要使用它。 – BGerrissen 2010-11-04 11:17:08

0
// 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'); 
} 
2

將if()語句放置在#Forwardbutton的點擊處理程序中,以測試#Contentshowroom的左側位置。

如果你正在使用jQuery:

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

當您單擊Forwardbutton所以,現在,它將檢查Contentshowroom的左.offset()位置,看它是否小於或等於1960px。如果是這樣,它將動畫左邊的位置一個額外的980px

jQuery's .offset() method爲您提供相對於bodytop/left職位。如果您希望它相對於其父容器,則使用jQuery's .position() method

+0

+1但是,我也會加...'function(e){e.preventDefault()});' – 2010-11-04 11:05:27

+0

@aSeptik - 當然值得注意,但我們並不完全確定被點擊的是什麼,所以它可能會沒有必要。雖然不會傷害。 :o) – user113716 2010-11-04 11:08:51

+0

+ 1相同.offset()的想法,你可能已經第一個提到它,我不知道。 – BGerrissen 2010-11-04 11:17:42

0

如果這是在最開始一次運行,那麼

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); 
}