我將假設.galleryButtonLeft
元素與它們的href
屬性的鏈接設置爲散列(#
)。無論是return false
或event.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
必須是最後一次調用,因爲它會停止執行事件處理程序。
小問題:'300px'後面會出現一個尾隨的逗號,這會在某些版本的IE中導致錯誤。 – Sparky 2012-02-10 18:52:23
您還應該提供相關位的HTML代碼。 – Sparky 2012-02-10 18:53:19
您可能在按鈕內部有一個'href =「#」',當點擊它時,會將您帶回到頁面的頂部。請參閱下面的@ gion_13回答。 – Sparky 2012-02-10 18:56:56