HTML 锚导航不适用于 CSS 粘性堆栈

HTML Anchors Navigation Not Working With CSS Sticky Stack

我正在构建一个顶部有导航栏的网站,然后当我在页面上向下导航时,导航栏下方的部分标题被堆叠为粘性。我注意到,当在元素中使用“顶部”CSS 标记时,HTML 锚点被破坏。

我已经在 this jsfiddle 中编写了示例代码。加载页面后,您可以通过顶部导航栏导航至 ID1、ID2、ID3 和 ID4。问题是,例如,当您到达 ID2 时,您无法返回到 ID1,或者无法从 ID3 返回到 ID1 或 ID2。基本上,您不能使用任何使用“顶部”CSS 标签的堆叠式粘性元素的锚点,该标签位于页面的较高位置。

这对我来说没有意义。关于为什么会这样以及如何解决的任何想法?

提前感谢所有回复。

代码示例:

<!DOCTYPE html>
<html lang="en">

<head>
  <style>
    .topnav {
      background-color: #f1f1f1;
      position: sticky;
      top: 0;
      width: 100%;
      z-index: 99;
      border: #f1f1f1;
}
    .stickytitle{
      list-style-type: none;
      float: left;
      margin: 0;
      width: 100%;
      overflow: hidden;
      background-color: seagreen;
      position: sticky;
      top: 20px;
      border-radius: 0px;
      font-size: 18px;
      font-weight: bold;
      color: #eee;
      z-index: 98;
    }
  </style>
</head>

<div class="topnav">
  <a href="#">Home</a>
  <a href="#id1">ID1</a>
  <a href="#id2">ID2</a>
  <a href="#id3">ID3</a>
  <a href="#id4">ID4</a>
</div> 

<h1 class="stickytitle" id="id1">ID1</h1>
<p>TO TEST INSERT LONG TEXT HERE OR CHECK THE JSFIDDLE REFERRED ABOVE</p>
<h1 class="stickytitle" id="id2">ID2</h1>
<p>TO TEST INSERT LONG TEXT HERE OR CHECK THE JSFIDDLE REFERRED ABOVE</p>
<h1 class="stickytitle" id="id3">ID3</h1>
<p>TO TEST INSERT LONG TEXT HERE OR CHECK THE JSFIDDLE REFERRED ABOVE</p>
<h1 class="stickytitle" id="id4">ID4</h1>
<p>TO TEST INSERT LONG TEXT HERE OR CHECK THE JSFIDDLE REFERRED ABOVE</p>

</html>

正如@CBroe 指出的那样,您需要创建不会变粘的sections/wrappers。

section {
  min-height: 50vh;
}
.topnav {
  background-color: #f1f1f1;
  position: sticky;
  top: 0;
  width: 100%;
  z-index: 99;
  border: #f1f1f1;
}
.stickytitle{
  list-style-type: none;
  float: left;
  margin: 0;
  width: 100%;
  overflow: hidden;
  background-color: seagreen;
  position: sticky;
  top: 20px;
  border-radius: 0px;
  font-size: 18px;
  font-weight: bold;
  color: #eee;
  z-index: 98;
}
<div class="topnav">
  <a href="#">Home</a>
  <a href="#id1">ID1</a>
  <a href="#id2">ID2</a>
  <a href="#id3">ID3</a>
  <a href="#id4">ID4</a>
</div> 

<section id="id1">
  <h1 class="stickytitle">ID1</h1>
  <p>TO TEST INSERT LONG TEXT HERE OR CHECK THE JSFIDDLE REFERRED ABOVE</p>
</section>
<section id="id2">
  <h1 class="stickytitle">ID2</h1>
  <p>TO TEST INSERT LONG TEXT HERE OR CHECK THE JSFIDDLE REFERRED ABOVE</p>
</section>
<section id="id3">
  <h1 class="stickytitle">ID3</h1>
  <p>TO TEST INSERT LONG TEXT HERE OR CHECK THE JSFIDDLE REFERRED ABOVE</p>
</section>
<section id="id4">
  <h1 class="stickytitle">ID4</h1>
  <p>TO TEST INSERT LONG TEXT HERE OR CHECK THE JSFIDDLE REFERRED ABOVE</p>
</section>