接受的答案不適合我,因爲我的網頁在點擊時略微跳躍,搞亂了我的滾動動畫。
我決定使用window.history.replaceState
更新整個URL,而不是使用window.location.hash
方法。從而繞過瀏覽器觸發的hashChange事件。
// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {
// Prevent default anchor handling (which causes the page-jumping)
event.preventDefault();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
// Smooth scrolling to anchor
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
// Update URL
window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
}
}
});
我跑這個當前頁面上的下面,才正是你想要的(沒有重新加載頁面):$( 「A」)點擊(函數(事件){event.preventDefault();窗口。 location.hash = $(this).attr('href');})。也許在你的代碼運行的時候,頁面還沒有加載?檢查中有多少項目在'$(「ul.questions李一」)' – 2009-12-21 09:49:48