这更多是一个解决问题的问题。我正在尝试利用浏览器提供的本机页面内滚动功能,以使移动用户可以更轻松地跳到他们需要的内容。
问题是我在页面上有一个粘性标头,因此使用本机<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>
如果您知道标题的高度,则可以如下更改锚点的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>