twitter-bootstrap 使用 Bootstrap 4 固定导航栏在 HTML 中偏移滚动锚点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49331572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:18:49  来源:igfitidea点击:

Offset scroll anchor in HTML with Bootstrap 4 fixed navbar

csstwitter-bootstrapbootstrap-4

提问by Kevin

So, I have this single page that consists of a few sections. Users can go to these sections by scrolling themselves or clicking in the navbar (a href with anchor). Due to the Bootstrap 4 navbar being fixed to the top, the content gets placed under it. Is there a way I could offset anchors by -54px, so that whenever I click on an anchor link, it would show the content below the navbar (X:54px) and not under the navbar (X:0px).

所以,我有这个由几个部分组成的页面。用户可以通过滚动自己或单击导航栏(带有锚点的 href)来访问这些部分。由于 Bootstrap 4 导航栏固定在顶部,内容被放置在其下方。有没有一种方法可以将锚点偏移 -54px,以便每当我单击锚点链接时,它都会显示导航栏下方 (X:54px) 而不是导航栏下方 (X:0px) 的内容。

Made this codepen to show the problem I'm facing:
https://codepen.io/anon/pen/XEjaKv
Whenever you click an anchor link, it will take you to the section, however, the navbar is covering the text..

制作此代码笔以显示我面临的问题:
https://codepen.io/anon/pen/XEjaKv
每当您单击锚链接时,它都会将您带到该部分,但是,导航栏覆盖了文本..

All sections are 100 viewheight.

所有部分都是 100 视高。

SCSS used:

使用的 SCSS:

.container{
  section{
    height: 100vh;
    &#section1{
      margin-top: 54px; // we need to offset the first section by 54px because of the navbar..
    }
    &#section1, &#section3{
      background-color: #ddd;
    }
    &#section2, &#section4{
      background-color:#ccc;
    }
  }
}
html{
  scroll-behavior:smooth;
}

采纳答案by Zim

There are a few different ways to solve it, but I think the best way is to put a hidden pseudo element ::beforeeach section. This is a CSS only solution, no JS or jQuery...

有几种不同的方法可以解决它,但我认为最好的方法是在::before每个部分放置一个隐藏的伪元素。这是一个只有 CSS 的解决方案,没有 JS 或 jQuery ...

section:before {
    height: 54px;
    content: "";
    display:block;
}

https://www.codeply.com/go/J7ryJWF5fr

https://www.codeply.com/go/J7ryJWF5fr

That will put the space needed to account for the fixed-top Navbar. You'll also want to remove the margin-topoffset for #section1since this method will work consistently for allsections and allow the scrollspy to work.

这将放置用于说明固定顶部导航栏所需的空间。您还需要删除margin-top偏移量,#section1因为此方法将始终适用于所有部分并允许 scrollspy 工作。



Related
How do I add a data-offset to a Bootstrap 4 fixed-top responsive navbar?
Href Jump with Bootstrap Sticky Navbar

相关
如何将数据偏移添加到 Bootstrap 4 固定顶部响应式导航栏?
带有 Bootstrap 粘性导航栏的 Href 跳转

回答by Taki

you can use jQueryto override the default behavior so you don't have to change the layout ( margin, padding .. etc.)

您可以使用jQuery覆盖默认行为,这样您就不必更改布局(边距、填充...等)

  var divId;

  $('.nav-link').click(function(){    
    divId = $(this).attr('href');
     $('html, body').animate({
      scrollTop: $(divId).offset().top - 54
    }, 100);
  });

https://codepen.io/anon/pen/NYRvaL

https://codepen.io/anon/pen/NYRvaL

回答by roland

Thissolution adds a padding and removes the gap by a negative margin at the top. This worked best for me.

解决方案添加了一个填充并通过顶部的负边距消除了间隙。这对我来说效果最好。

section {
    padding-top: 56px;
    margin-top: -56px;
}

.offset {
    height: 54px;
}

/* START SNIPPET */
section {
    padding-top: 56px;
    margin-top: -56px;
}
/* END SNIPPET */

#section1 p, #section3 p {
    background-color: #ddd;
}
#section2 p, #section4 p {
    background-color: #ccc;
}
p {
    min-height: 15rem;
}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  </head>
  <body>
 <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarsExampleDefault">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item">
            <a class="nav-link" href="#section1">Section 1</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#section2">Section 2</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#section3">Section 3</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#section4">Section 4</a>
          </li>
        </ul>
      </div>
    </nav>
 
  <div class="container">
    <div class="offset col-12"></div>
    <section id="section1" class="row">
      <p class="col-12">
        Section 1
      </p>
    </section>
    <section id="section2" class="row">
      <p class="col-12">
        Section 2
      </p>
    </section>
    <section id="section3" class="row">
      <p class="col-12">
        Section 3
      </p>
    </section>
    <section id="section4" class="row">
      <p class="col-12">
        Section 4
      </p>
    </section>
  </div>
 
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

回答by Jacob Shore

I like to dynamically offset the height header (or navbar) like this:

我喜欢像这样动态偏移高度标题(或导航栏):

$('.nav-link').click(function(e){
    let divCoords = $(e.target.hash).offset();
    let height = $('header').height();
    e.preventDefault();
    window.scrollTo({
    left: divCoords.left, 
    top: divCoords.top - height,
    behavior: 'smooth'
    });
});

回答by scramlo

Usually when using a sticky header like that you'll want to find the height of your navbar and offset the entire view accordingly. Something like

通常当使用像这样的粘性标题时,您会想要找到导航栏的高度并相应地偏移整个视图。就像是

body {
  margin-top:2rem;
}

Your other option would be to use JavaScript.

您的另一个选择是使用 JavaScript。