我有 2 个 div。包含页面上部的一个。另一个直接位于顶部 div 下方。第二个 div 位于页面下方大约 1.5 个视口(viewport)处。但是当我尝试在按下导航按钮时使页面滚动到第二个 div 时。它将我带到页面顶部。即使它引用了第二个 div 的 scrollTop 属性。
最佳答案
scrollTop 永远等同于位置0。如果你想滚动到不同的div,那么你需要使用offset 并滚动到hash 位置。如果您使用的是 Bootstrap,则可以为此使用 ScrollSpy。如果不是,那么您可以使用此代码来处理平滑滚动到散列位置。
在您的情况下,散列应该是 div 的 ID - 您将通过在按钮/链接上设置 href 来匹配您希望按钮/链接滚动到的 div 的 ID 来定位它。
因此,您的链接可能如下所示:
<a href="#somediv">Some Link</a>
你的 div 可能看起来像这样:
<div class="someclass" id="somediv"></div>
并且这个 JS 将处理滚动到正确的位置:
// 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 -80
}, 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
};
});
}
}
});
关于javascript - scrollTop 等于 0,即使 div 位于页面下方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44464390/