给定一个固定的导航和一些带有 anchor 的部分;单击哈希链接时 - 固定导航与部分 anchor 重叠。
我看过一些类似的帖子,但似乎找不到适合我的特定情况的解决方案。
我无法覆盖 .anchor
样式或使用 JavaScript 修复该偏移量或 add any additional HTML elements由于元素限制。
虽然我可以添加一个伪元素到.anchor
- the hack with a height and a negative margin平衡它在我的情况下不起作用,因为 .anchor
具有顶部填充和边框。
<h3 class="anchor" id="section-1">Title 1</h3>
<p>Description 1</p>
<h3 class="anchor" id="section-2">Title 2</h3>
<p>Description 2</p>
<h3 class="anchor" id="section-3">Title 3</h3>
<p>Description 3</p>
.nav {
position: sticky;
}
.anchor {
border-top: 1px solid #333940;
margin-top: 2rem;
padding-top: 2rem;
}
.anchor::before {
}
谁能帮我弄清楚是否有纯 CSS 方式来修复 anchor 的偏移量?
最佳答案
试试这个。
<script type="text/javascript">
$('a[href^="#"]').on('click',function (e) {
// e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top-80
}, 1000, 'swing', function () {
window.location.hash = target;
});
});
top-80就是你想要的空间高度
关于html - 修复了导航和 anchor 偏移问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56878287/