Javascript 页内滚动偏移量

标签 javascript html css scroll anchor

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

问题是我在页面上有一个粘性标题,所以使用 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>

最佳答案

如果您知道 header 的高度,那么您可以像下面这样更改 anchor 的 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>

关于Javascript 页内滚动偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59773790/

相关文章:

javascript - ng-grid是否支持按行进行单元格过滤( Angular 过滤)

javascript - 尝试反转 HTML/CSS 切换器的 JavaScript 触发器

javascript - 如何将选项标签的相同数据标识归因于其他元素?

html - Bootstrap Carousel 图像过渡幻灯片不起作用

html - 如何使导航栏透明?

javascript - 动态生成的 html 表无法获取选定的 td 值

javascript - 将随机值插入表 JS

javascript - 字符串不是 Coffeescript 中的函数

javascript - 重定向到父窗口

javascript - 如何在不缩放的情况下创建窗口分辨率大小的 Canvas ?