所以我在一个有固定导航栏的网站上工作:
http://abnetworksa.rewind9.com/servicios/infraestructura/
除了固定的导航栏,还有一个“粘性”侧边栏。此侧边栏链接是将用户重定向到同一页面中特定内容的 anchor 。
似乎一切正常。但是,当单击其中一个侧边栏链接时,目标内容标题隐藏在固定导航栏下。有什么方法可以设置和偏移此侧边栏链接吗?
我试过了
var offset = 380;
$('.sidebar-nav li a').click(function(event) {
event.preventDefault();
$($(this).attr('href'))[0].scrollIntoView();
scrollBy(0, +offset);
});
但它不起作用似乎开始从下到上进行一些奇怪的计算。
有什么帮助吗?
非常感谢!
最佳答案
标题不固定。我看到您正在使用 Bootstrap ,因此您可以使用 navbar-fixed-top
类使其具有粘性。您需要将 header
标签上的类从 navbar-static-top
更改为 navbar-fixed-top
。
回答你问题的第二部分,因为你在你的元素中使用 Bootstrap 这个答案https://stackoverflow.com/a/14805098/3070770会帮助你。
$(".sidebar-nav li a").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
var heightOfNavigationMenu = $('.navbar').height
// animate
$('html, body').animate({
scrollTop: $(hash).offset().top - heightOfNavigationMenu
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});
注意变量 heightOfNavigationMenu
。还有 ScrollIntoView某些浏览器不支持。
关于javascript - 使用 .affix 和固定导航栏的侧边栏偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34910114/