所以我还没有找到一种方法来使用element.scrollIntoView({behavior: 'smooth'})
,同时还要考虑固定的导航。滚动效果很好,但固定导航总是覆盖我想要滚动到的标题。我在网上看了一下,发现了一些其他解决方案。但我还没有找到一个包含平滑滚动行为的方法。我想避免突然跳转到滚动条。
答案 0 :(得分:1)
为了避免这种行为,您可以将标头静态定位,并将其置于 滚动的repr
之上,而不是使用固定标头。
div
function doIt() {
const header = document.getElementById("header1");
header.scrollIntoView({
behavior: "smooth"
});
}
body {
display: flex;
flex-direction: column;
overflow: none;
height: 100%;
position: absolute;
}
nav {
height: 100pt;
flex-shrink: 0;
background-color: black;
color: white;
}
section#content {
flex-grow: 1;
overflow-y: auto;
}
将此与具有固定导航栏的版本对比:
<body>
<nav>
This is a nav bar.
<a href="#" onclick="doIt()">go to header1</a>
</nav>
<section id="content">
<h1 id="header1">
This is a header.
</h1>
<p>
This is some text. Lorem ipsum dolor sit amet, nam decore labore accumsan no. Ad perfecto inciderint eum, quaeque reprimique an sea. Et omnis ridens option vim, ex vix dico oblique repudiandae, idque accommodare ut usu. Erant consequat intellegam vis
id, dolorum ancillae mandamus mel eu. Quo elit solum ridens ad, nibh docendi recusabo eu qui. Dolorem quaestio pri ea, etiam aeterno vim ei. Te oporteat maiestatis constituam sea, mea euripidis vulputate id. Mea populo persequeris instructior ea.
Ut graecis cotidieque pri.</p>
<h1 id="header2">
This is another header.
</h1>
<p>
Quo cu iriure conceptam, inani molestiae usu te, cum et dolorum denique epicuri. Adhuc iusto vel ei, eos ex efficiantur theophrastus, tale sanctus erroribus eos cu. Mollis regione accusam nam ex. Te vim dolorem qualisque, ex per odio putent intellegat,
et percipitur liberavisse nec. Usu porro causae ne, no possim definiebas his. Wisi utroque has an. An qui evertitur elaboraret suscipiantur, eam adipisci conceptam eu, graeco nusquam inimicus ut usu. Officiis molestiae ullamcorper vis eu, no laudem
graeci contentiones per, id salutandi dissentiunt cum. An eam natum alterum, fugit paulo ad his. Intellegebat definitiones ex sed, ea per suas tincidunt, mei in viderer partiendo conclusionemque. Ullum appetere in nec, stet vivendo consetetur eu
eos.
</p>
</section>
</body>
function doIt() {
const header = document.getElementById("header1");
header.scrollIntoView({
behavior: "smooth"
});
}
nav {
height: 100pt;
position: fixed;
top: 0;
background-color: black;
color: white;
width: 100%;
}
section#content {
overflow-y: auto;
width: 100%;
margin-top: 100pt;
}
至少在Firefox中,这个版本似乎也有效。也就是说,只需在容器顶部插入填充或边距即可。但是,这可能不太可靠。
答案 1 :(得分:0)
当我使用固定标题时,我的身高与固定标题的高度相同。因此,如果导航栏高64像素,我在主体上使用64px填充顶部。
.navbar {
height: 64px;
}
body {
padding-top: 64px;
}
应该很容易理清。