这更像是一个解决问题的问题。我正在尝试利用浏览器提供的 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/