如何在不重叠的情况下在滚动(粘性顶部)顶部定位两个引导导航栏?

时间:2021-04-24 22:45:09

标签: twitter-bootstrap bootstrap-4

我使用引导程序 4 粘顶类将 2 个导航栏设置为滚动顶部。但问题是当我滚动时,第二个上升(重叠)在第一个之上,这就是为什么我看不到第一个。第二个应该放在卷轴上第一个的下方。有没有办法做到这一点? 示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  
</head>
<body style="height:1500px">

<div class="container-fluid">
  <br>
  <h3>Sticky Navbar</h3>
  <p>A sticky navigation bar stays fixed at the top of the page when you scroll past it.</p>
  <p>Scroll this page to see the effect. <strong>Note:</strong> sticky-top does not work in IE11 and earlier.</p>
</div>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark sticky-top">
  <a class="navbar-brand" href="#">Logo</a>
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="#">Link</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link</a>
    </li>
  </ul>
</nav>

<div class="container-fluid"><br>
  <p>Some example text. Some example text. Some example text. Some example text. Some example text.</p>
  <p>Some example text. Some example text. Some example text. Some example text. Some example text.</p>
  <p>Some example text. Some example text. Some example text. Some example text. Some example text.</p>
  <p>Some example text. Some example text. Some example text. Some example text. Some example text.</p>
</div>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark sticky-top sticky-top-2">
  <a class="navbar-brand" href="#">Logo 2</a>
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="#">Link</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link</a>
    </li>
  </ul>
</nav>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

在 bootstrap css 中,你会发现如下代码

@supports ((position: -webkit-sticky) or (position: sticky)) {
  .sticky-top {
    position: -webkit-sticky;
    position: sticky;
    top: 0px;
    z-index: 1020;
  }
}

对于第二个导航栏,您可以复制代码并粘贴额外的 css 或自定义 css,然后将类重命名为 .sticky-top-2 并设置 top: 100px 或您为第一个导航栏设置的高度值,然后如果您想要第一个导航栏应该下拉到第二个导航栏上,只需将 z-index 值设置为小于 1020,例如 z-index: 1019;所以,最终的代码就像

@supports ((position: -webkit-sticky) or (position: sticky)) {
  .sticky-top2 {
    position: -webkit-sticky;
    position: sticky;
    top: 100px;
    z-index: 1019;
  }
} 

现在将第二个导航栏调用 .sticky-top 的 HTML 代码更改为 **

<块引用>

.sticky-top2

**

答案 1 :(得分:0)

问题是两者都有top:0;第二个导航栏必须远离第一个导航栏的高度。

如果需要更详细的帮助,请输入代码