首页 > 解决方案 > Javascript页内滚动偏移

问题描述

这更像是一个解决问题的问题。我正在尝试利用浏览器提供的本机页内滚动功能,让移动用户更轻松地跳转到他们需要的内容。

问题是我在页面上有一个粘性标题,所以使用 native <a id="section1"></a>,访问#section1意味着滚动位置在粘性标题后面。

有没有办法使用普通的 JS(如果可能的话,甚至是 CSS!),将滚动位置偏移一定数量的像素?或者是否有更优雅的 JS 解决方案适用于 IE11、Edge、Chrome 和 FF?

<header> ... </header> <!-- site-wide sticky header using position: sticky -->
<main>
  <nav> <!-- page-specific sticky nav using position: sticky (placed under <header />) -->
    <a href="#top">Top</a>
    <a href="#bottom">Bottom</a>
  </nav>
  <div class="content">
    <section>
      <a id="top"></a>
      ...
      ...
      ...
    </section>
    ...
    <section>
      <a id="bottom"></a>
      ...
      ...
      ...
    </section>
  </div>
</main>

标签: javascripthtmlcssscrollanchor

解决方案


如果您知道标题的高度,那么您可以更改top锚点的高度,如下所示:

header {
  position: sticky;
  position: -webkit-sticky;
  top: 0; /* required */
  background: yellow;
  width: 100%;
  height: 40px;
}

nav {
  position: sticky;
  position: -webkit-sticky;
  top: 40px; /* required */
  background: red;
  width: 100%;
  height: 20px;
}

section > a {
  position: relative;
  top: -60px;
}

section > div {
  height: 500px;
  width: 100%;
}

#topDiv {
  background: blue;
}

#bottomDiv {
  background: green;
}
<header> ... </header> <!-- site-wide sticky header using position: sticky -->
<main>
  <nav> <!-- page-specific sticky nav using position: sticky (placed under <header />) -->
    <a href="#top">Top</a>
    <a href="#bottom">Bottom</a>
  </nav>
  <div class="content">
    <section>
      <a id="top"></a>
      <div id="topDiv" style="height: 500px; width: 100%" >
        Content
      </div>
    </section>
    <section>
      <a id="bottom"></a>
      <div id="bottomDiv" style="height: 500px; width: 100%" >
        Content
      </div>
    </section>
  </div>
</main>


推荐阅读