接受的答案不适合我,因为我的网页在点击时略微跳跃,搞乱了我的滚动动画。
我决定使用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