Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

navigation - How do I add a data-offset to a Bootstrap 4 fixed-top responsive navbar?

So, in Bootstrap v3, you would just add a data-offset attribute to the nav tag, with the pixel offset, in this case 54px,

<nav data-offset="54"></nav>

However, in Bootstrap v4, this data-offset attribute is missing, and doesn't work. I've had a look through the v4 docs, and just can't seem to find anything! I've also tried using data-offset and offset attributes, but these don't work either.

Here is the html code of the nav

<nav class="navbar navbar-light bg-faded navbar-fixed-top">
  <button type="button" data-toggle="collapse" data-target="#nav-collapse" aria-controls="#nav-collapse" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler hidden-md-up">&#9776;</button>
  <div id="nav-collapse" class="collapse navbar-toggleable-sm">
    <ul class="nav navbar-nav pull-md-right">
      <li class="nav-item"><a href="#page-top" class="nav-link page-scroll">home</a></li>
      <li class="nav-item"><a href="#about" class="nav-link page-scroll">about</a></li>
      <li class="nav-item"><a href="#services" class="nav-link page-scroll">services</a></li>
      <li class="nav-item"><a href="#productssolutions" class="nav-link page-scroll">products + solutions</a></li>
      <li class="nav-item"><a href="#contact" class="nav-link page-scroll">contact</a></li>
    </ul>
  </div>
</nav>

How would I go about adding a data offset of 54px? Is there an alternative that could be used, say a simple script tag needing to be added to my html with a few lines of js?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So the way I ended up fixing it was by adding a separate element on top of each of the sections;

<span class="anchor" id="SECTION"></span>
<section id="SECTION" REST OF SECTION HERE>
    ....

The id in the section element is to allow for scroll spy to work correctly.

and by adding this to my css file;

span.anchor {
    margin-top: -54px; /* height of nav, in this case 54px */
    display: block;
    height: 54px; /* height of nav, in this case 54px */
    visibility: hidden;
    position: relative;
}

and then, hey presto! It worked, and one nice thing about this solution is that it doesn't affect anything visually, it just changes the anchor point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...