【问题标题】:Link to id but navbar in the way链接到 id 但导航栏挡住了
【发布时间】:2022-02-12 05:37:40
【问题描述】:
我有一个导航栏,其中包含指向带有id="about" 的文章的链接,但我的导航栏是固定顶部的,所以当我单击链接时,我的导航栏位于该部分的标题前面。
我用这个解决了这个问题:<span id="about" class="anchor"></span>
.main-content article .anchor{
position: absolute;
top: -106px;
}
但对于 scrollspy,我需要链接的 href 与我想要“scrollspy”的部分的 id 相同,但我不能两次使用相同的 id。
我该如何解决这个问题?有没有办法将-100px 添加到您的href 或类似的东西?
【问题讨论】:
标签:
javascript
html
css
twitter-bootstrap
【解决方案1】:
您可以在 about 内容上方添加这样的“假”锚:
<div style="margin-top: -95px; position: absolute;" id="about"></div>
这将为您上面的部分添加一个边距,经过一些调整后,您可以更改 px 值以适应您的情况。
【解决方案2】:
您可以像这样尝试使用 jquery:
$(document).ready(function() {
$('a[href^="#"]').click(function() {
var target = $(this.hash);
$('html, body').animate({ scrollTop: target.offset().top-100 }, 1000);
}
}
【解决方案3】:
我也遇到过这个问题,我发现只需在要跳转到的位置上方放置一个锚标记,然后使用值将 scroll-margin-top 添加到我的 CSS 中很容易。
#jumpto {
scroll-margin-top: (insert value here);
}
<nav>
<ul>
<li><a href="#jumpto">Nav Link</a></li>
</ul>
</nav>
<a id="jumpto"></a>
<section>
<h2>
This is where I want to jump to but the stupid navbar is in the way!
</h2>
</section>