粘性标题输入在输入上滚动

缺口

我有一个带有搜索输入的标头。为确保锚定标记(<a href='#section'>)不会将内容隐藏在标题顶部之后,我添加了以下CSS。

html {
    scroll-padding-top: 48px
}

但是,如果粘性标题包含输入,则当用户键入输入时,整个页面将滚动。

有没有一种方法可以保留当前的滚动填充行为并防止在使用输入时自动滚动?最好仅使用HTML和CSS。

html {
  scroll-padding-top: 48px;
}

body {
  margin: 0;
}

header {
  position: sticky;
  top: 0;
  background: #eeeeee;
  padding: 8px 16px;
}

main {
  padding: 8px 16px;
}

main article,
main div {
  padding: 32px 0;
  border-bottom: 1px solid lightgray;
}

main div {
  background: #ddddff;
}
<html>

<body>
  <header>
    <input type='text' placeholder='type here, page scrolls' />
  </header>
  <main>
    <article>
      <p><a href='#anchor-point'>click me to skip down to the lower section</a></p>
    </article>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
    <div id='anchor-point'>
      I also want to link to here. This section should not get cut off by the sticky header. The entire thing should be visible.
    </div>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
  </main>
</body>

</html>

相关文章

在Chrome中编辑粘性输入元素会使页面滚动到顶部-解决方案使用JS拦截输入。如果可能的话,我宁愿不使用JS。此外,该帖子中描述的原始错误似乎已修复。

lastr2d2

这可能不是一个完整的答案,因为它不能回答问题“为什么?”。

但是,如果scroll-padding-top: 48px从html样式中删除,然后scroll-margin-top在目标锚点上添加,则将获得预期的结果。

#anchor-point{
 scroll-margin-top: 48px;
}

也可以避免将id选择器与:target伪类选择器一起使用

:target {
 scroll-margin-top: 48px;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章