2012-02-10 117 views
0

奇怪的行爲,我有一個簡單的動畫:與jQuery動畫

$(function() { 
    $(".galleryButtonLeft").mousedown(function(){ 
     $("#theGallery").animate({ 
       marginLeft: "-=300px", 
     }, 1000); 
    }); 
}); 

theGallery只是一個divposition:relative

沒什麼特別的:

  <div style="position:relative"> 
       <img/> 
     </div> 

當我點擊我的galleryButtonLeft將其300px向左移動,頁面立即去頂,如果我有我的瀏覽器unmaximized並滾動到頁面的中間在我的畫廊坐落。我希望頁面保持在原來的位置,並且每次單擊該按鈕時都不會跳轉到頂部。我怎麼做?

+0

小問題:'300px'後面會出現一個尾隨的逗號,這會在某些版本的IE中導致錯誤。 – Sparky 2012-02-10 18:52:23

+0

您還應該提供相關位的HTML代碼。 – Sparky 2012-02-10 18:53:19

+0

您可能在按鈕內部有一個'href =「#」',當點擊它時,會將您帶回到頁面的頂部。請參閱下面的@ gion_13回答。 – Sparky 2012-02-10 18:56:56

回答

2

我將假設.galleryButtonLeft元素與它們的href屬性的鏈接設置爲散列(#)。無論是return falseevent.preventDefault()取消鏈接(S)的默認行爲:

$(function() { 
    $(".galleryButtonLeft").mousedown(function(){ 
     $("#theGallery").animate({ 
      marginLeft: "-=300px"//notice I removed the trailing comma here, it'll come back to haunt you if you don't (some browsers throw errors for these) 
     }, 1000); 
    }).click(false);//this returns false for any click event for the/these element(s), stopping the default behavior of the element(s) 
}); 

返回false內一個jQuery事件處理的是同樣的事情,呼籲event.preventDefault()event.stopPropagation()

如果你想使用event.preventDefault()而不是返回false,那麼你必須傳遞在event對象在匿名函數(事件處理程序):

$(function() { 
    $(".galleryButtonLeft").mousedown(function(){ 
     event.preventDefault(); 
     $("#theGallery").animate({ 
      marginLeft: "-=300px"//notice I removed the trailing comma here, it'll come back to haunt you if you don't (some browsers throw errors for these) 
     }, 1000); 
    }).click(function (event) { 
     event.preventDefault(); 
    }); 
}); 

注意,您可以在事件的任何地方撥打event.preventDefault()處理程序,但返回false必須是最後一次調用,因爲它會停止執行事件處理程序。

+0

這工作到完美。非常感謝 – BoundForGlory 2012-02-10 20:09:58

+0

@ user1202717不客氣。 – Jasper 2012-02-10 20:12:39

2

如何添加

/*...*/mousedown(function(e){e.preventDefault(); /*...*/ 

$(".galleryButtonLeft").click(function(e){e.preventDefault();}); 

我認爲這個問題可能是你的觸發器(.galleryButtonLeft)是它具有href屬性設置爲東西起動的元素與#。這樣,當你點擊鏈接時,瀏覽器欄中的哈希值會發生變化,從而使瀏覽器跳起來。