3

JSfiddle 应该解释一下:http: //jsfiddle.net/UMW26/

或者

就像标题说的那样,如何防止固定导航栏在单击链接或通过 url 地址访问后覆盖文本/标题,这将跳转到它。

这是我使用的示例代码:

<!DOCTYPE html>

<style type="text/css">
body { margin: 0; }
#content { height: 1500px;margin-top: 20px;background-color:skyblue; }
#fix-nav-bar { position: fixed; width:100%; top:0; text-align:center; background-color: pink; }

#content-title { margin-top: 250px;font-weight:bold;font-size:16pt; }
</style>

<div id="fix-nav-bar">
fixed navigation bar
</div>

<div id="content">
<a href="#content-title">Click here to jump to Title:</a>

<div id="content-title">Sample Content Title/Name</div>
How do I prevent fixed navigation bar from covering title after clicking "<b>Click here to jump to Title</b>" but just keep it slightly above it?
</div>
4

3 回答 3

3

我用一些jquery通过以下方式解决了这个问题:

  1. 抓取 URL 并检查其末尾是否有 ID#divID并将其设置为变量
    var id = '#divID'

如果 ID 存在...

  1. 获取导航栏的高度(或随心所欲,下面使用 50px)
  2. 从您的 div 的 id 设置 scrollTop 属性。

$('html,body').animate({
  scrollTop: $(id).offset().top - 50
});

于 2018-11-27T19:41:41.970 回答
0

JS 解决方案:使用 div 代替导航栏中的链接。附加一个 onclick 函数,该函数滚动到元素的 y 坐标,减去导航栏的高度。

例子:

HTML

<div class="nav-links">
    <div class="link" onclick="goTo('#about')">About</div>
    <div class="link" onclick="goTo('#tours')">Tours</div>
    <div class="link" onclick="goTo('#contact')">Contact</div>
</div>

JS:

function goTo(id) {
  let destination = document.querySelector(id);
  let yCoord = destination.offsetTop - 70;
  window.scrollTo({
    top: yCoord,
    behavior: "smooth"
  });
}
于 2018-12-02T09:33:05.940 回答
0

我找到了当前最简单的解决方案

/* CSS */

html {
    scroll-padding-top: 44px; /* Replace with your fixed navbar height */
}

body {
    margin: 44px auto 0; /* Replace with your fixed navbar height */
}
于 2021-06-20T21:18:16.653 回答