html - 修复了导航和 anchor 偏移问题

标签 html css

给定一个固定的导航和一些带有 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/

相关文章:

html - CSS 中的剧本布局样式

jquery - onclick 事件,无法使用 jQuery 更改 .CSS 文件

javascript - 打印分层的 html5 Canvas

html - 下拉菜单不完全重叠菜单选项。 Z 索引设置

html - 带有子列表的 float li 元素

html - 我不想要的顶部边距

javascript - Webkit translateY + textarea 错误

html - 如何将单选按钮与 html 中的图像中间垂直对齐?

html - Django 模板中具有独特主页布局的网站

javascript - 我希望输出分钟和秒像 09 :09