ita*_*tai 10 javascript scroll
假设我有以下功能:
window.smoothScroll = function(target) {
var scrollContainer = target;
scrollContainer.scrollIntoView(true);
}
Run Code Online (Sandbox Code Playgroud)
如何使页面滚动到元素上方 20px,而不是滚动到元素本身?
谢谢
Mik*_*ans 12
由于CSS更新而编辑
使用scroll-margin-top,在原始答案写完后引入。
2018年原始答案
获取元素的尺寸信息,然后告诉窗口滚动到元素的top负 20,而不是将其滚动到视图中:
function scrollToJustAbove(element, margin=20) {
let dims = element.getBoundingClientRect();
window.scrollTo(window.scrollX, dims.top - margin);
}
Run Code Online (Sandbox Code Playgroud)