带有边距的scrollIntoView

met*_*ard 5 javascript html5

我有一个网页,我想滚动到该网页上的某个元素。

通过使用该部分可以正常工作scrollIntoView;但我想在元素(20px或其他内容)上方添加一些空间

我目前正在做这样的事情:

const moveToBlue = () => {
  const blue = document.getElementById('blue')
  blue.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start'});
};
Run Code Online (Sandbox Code Playgroud)

但是,我想进一步向上滚动20像素(在此处查看我的演示

这可能吗?

col*_*nux 74

您可以scroll-margin在滚动目标元素上设置CSS 属性。例如

.blue {
  scroll-margin: 20px;
}
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin

  • 更具体一点:`scroll-margin-top: 20px;` (13认同)
  • 这应该是公认的答案。 (5认同)
  • 完美的。就我而言,scroll-padding-bottom 确保scrollIntoView 在我的滚动元素中具有该缓冲区。 (3认同)
  • 这就是我一直在寻找的东西!非常感谢! (2认同)
  • 老兄,你杀了它! (2认同)

wiz*_*z94 8

您始终可以scrollTo通过首先获取元素坐标,getBoundingClientRect然后添加滚动偏移量并获取滚动边距来使用。例如

const moveToBlue = () => {
  const blue = document.getElementById('blue');
  let position = blue.getBoundingClientRect();
  // scrolls to 20px above element
  window.scrollTo(position.left, position.top + window.scrollY - 20);
};
Run Code Online (Sandbox Code Playgroud)


Moh*_*ood 6

这对我的情况有帮助 \xe2\x80\x94\n
\nHTML

\n
<div class='stick-to-top'></>\n
Run Code Online (Sandbox Code Playgroud)\n

JavaScript

\n
document.getElementsByClassName('stick-to-top')[0].scrollIntoView({behavior: "smooth", block: "center"});\n
Run Code Online (Sandbox Code Playgroud)\n

CSS

\n
.stick-to-top {\n padding-bottom: 400px;\n}\n
Run Code Online (Sandbox Code Playgroud)\n