我试图让我的页面在单击链接时滚动到 anchor ,同时考虑到根据视口(viewport)宽度而变化的标题大小。这适用于桌面版本的 Chrome,但在移动版本中,不考虑标题高度,页面滚动到隐藏在标题下方的 anchor 的顶部。
这是我改编自 CSS Tricks 的代码:
var headerHeight = document.getElementById('header').clientHeight;
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top-headerHeight
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
页面的滚动偏移量应等于 headerHeight 变量的高度。如上所述,这在桌面版 Chrome 上完美运行,但在移动版本中滚动时没有偏移。
提前致谢。
编辑2:此实例中的问题来自滚动动画后更改焦点的回调。页面滚动,然后跳转到焦点元素,忽略标题偏移。现在唯一的问题是,如果我删除焦点回调,那么屏幕阅读器等将无法访问该页面。
最佳答案
测试您的动画函数,将 setTimeout 设置为 200 毫秒。
您的 animate 函数在 DOM 和插件 JS(如 slider 或其他)完全执行之前执行。
关于javascript - JQuery anchor 链接滚动到错误位置(仅限某些设备),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686912/