我有一个网页,我想滚动到该网页上的某个元素。
通过使用该部分可以正常工作scrollIntoView
;但我想在元素(20px
或其他内容)上方添加一些空间
我目前正在做这样的事情:
const moveToBlue = () => {
const blue = document.getElementById('blue')
blue.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start'});
};
Run Code Online (Sandbox Code Playgroud)
这可能吗?
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
您始终可以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)
这对我的情况有帮助 \xe2\x80\x94\n
\nHTML
<div class='stick-to-top'></>\n
Run Code Online (Sandbox Code Playgroud)\nJavaScript
\ndocument.getElementsByClassName('stick-to-top')[0].scrollIntoView({behavior: "smooth", block: "center"});\n
Run Code Online (Sandbox Code Playgroud)\nCSS
\n.stick-to-top {\n padding-bottom: 400px;\n}\n
Run Code Online (Sandbox Code Playgroud)\n