Принятый ответ не сработал для меня, так как моя страница слегка подпрыгнула при нажатии, что испортило мою анимацию прокрутки.
Я решил обновить весь URL, используя window.history.replaceState
, а не метод 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);
}
}
});