我有带条目的导航栏。当我点击项目时,它会将我滚动到div。例如,我点击联系人,它滚动我联系。我的问题是我有固定的导航栏。我的导航栏隐藏了标题的标题。因此,当我点击联系人时,它会将我向下滚动以联系,但标题会在导航栏后面。
这是我的脚本我需要添加像滚动的东西 - 55px或类似的东西,但我不知道如何。
<script>
// 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
}, 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
};
});
}
}
});
</script>
答案 0 :(得分:0)
您可以首先检查点击的链接是否为/contact
,然后应用不同的滚动:
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
let scrollOffset = 0;
if ($(this).attr('href') === '/contact') {
scrollOffset = 55;
}
$('html, body').animate({
scrollTop: target.offset().top + scrollOffset
}, 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
};
});
}
这不是最优雅的解决方案,但应该可以解决这个问题。
答案 1 :(得分:0)
如果你也可以分享html,那就很容易理解了。无论如何,据我所知,问题在于固定导航栏。使用定位绝对/固定时,div将超出文档流。要在标题后立即启动元素,您需要为元素容器提供一个与标题高度相等的margin-top。这是最简单的解决方案。你不需要对js做任何事情。