2010-10-18 121 views
1

我似乎無法使preventDefault()與以下代碼一起工作......瀏覽器仍然希望在點擊後跳轉到頁面的頂部。有想法該怎麼解決這個嗎?爲什麼不能阻止默認爲jQuery工作?

$('#controls a').click(function(event){ 

event.preventDefault(); 

var r = $(this).attr('rel'); 

var c = $('#container').attr('class'); 
// Prevent redundant actions 
if (r != c) { 
    // Toggle 'active' class to show selection 
    $('#controls a').removeClass('active'); 
    $(this).addClass('active'); 
    // Fade out function then callback to change the view mode 
    $('#container').fadeOut(100, function(){  
    $('#container').removeAttr('class'); 
    $('#container').addClass(r); 
    // Fade the container back in 
    $('#container').fadeIn(100); 
    }); 
} 

}); //end list view 
+1

您可以添加相關的HTML,並確定頁面中沒有任何JS錯誤嗎? – JAL 2010-10-18 16:37:52

+0

代碼的其餘部分是否工作? – user113716 2010-10-18 16:40:41

+0

你點擊後是否在你的URL中附加了'#'(或其他...)?如果沒有,preventDefault正常工作... – Shog9 2010-10-18 16:42:34

回答

2

問題(可能,這部分是猜測)不preventDefault(),但事實YOUT頁有總高度含量少了一會兒(13毫秒是精確的),改變動畫等等它淡出,但沒有得到display: none;一幀,這樣的:

$('#container').animate({ opacity: 0 }, 100, function(){  
    $('#container').removeAttr('class'); 
    $('#container').addClass(r); 
    // Fade the container back in 
    $('#container').animate({ opacity: 1 }, 100); 
}); 

這樣,你的#container0高度了一會兒,致使頁後退向上滾動僅僅是因爲網頁有整體更短。

+0

噢射擊我怎麼錯過那個你是正確的只是增加了最小高度來測試這個理論,它的工作你釘了它,謝謝 – Terry 2010-10-18 16:55:06

+0

@Terry - 上述解決方案是否解決它? – 2010-10-18 16:58:22

+0

是的,只是更新它,並確實工作 – Terry 2010-10-18 17:04:50