其他人都给出了 CSS 答案,但问题要求 JS
@assmmahmud 的答案只需稍加调整即可:gotoSpecificPosition 需要在第一条语句中更改为 offsetAnchor。
这对于为粘性标题调整所有 id 链接非常有帮助。
/* go to specific position if you load the page directly from address bar */
var navbarHeight = document.getElementById('mynavbar').clientHeight;
function offsetAnchor() {
if (window.location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - navbarHeight );
}
}
/* Captures click events on all anchor tag with a hash tag */
$(document).on('click', 'a[href^="#"]', function(event) {
// Click events are captured before hashchanges. Timeout
// causes offsetAnchor to be called after the page jump.
window.setTimeout(function() {
offsetAnchor();
}, 0);
});
window.setTimeout(offsetAnchor, 0);