【发布时间】:2021-03-28 08:44:33
【问题描述】:
假设我有以下功能:
window.smoothScroll = function(target) {
var scrollContainer = target;
scrollContainer.scrollIntoView(true);
}
如何让页面在元素上方滚动 20 像素,而不是滚动到元素本身?
谢谢
【问题讨论】:
标签: javascript scroll
假设我有以下功能:
window.smoothScroll = function(target) {
var scrollContainer = target;
scrollContainer.scrollIntoView(true);
}
如何让页面在元素上方滚动 20 像素,而不是滚动到元素本身?
谢谢
【问题讨论】:
标签: javascript scroll
获取元素的维度信息,然后告诉窗口滚动到元素的 top 负 20,而不是将其滚动到视图中:
function scrollToJustAbove(element, margin=20) {
let dims = element.getBoundingClientRect();
window.scrollTo(window.scrollX, dims.top - margin);
}
【讨论】:
getBoundingClientRect =)
好吧,为了平滑滚动,您可以使用 jQuery animate()。检查下面的代码:
window.smoothScroll = function(target, above, speed) {
let $scrollContainer = $target;
jQuery('html, body').animate({
scrollTop: jQuery(scrollContainer).offset().top - above
}, speed);
}
[注意:above 将是您的 20(因为您希望在目标上方 20px),speed 将是任何数字,例如:900 这样的数字。]
如果有帮助的话……!
【讨论】:
请更改变量定义。 $scrollContainer 和目标变量不一样,你可以在下面使用
window.smoothScroll = function(target, above, speed) {
let scrollContainer = target;
$('html, body').animate({
scrollTop: jQuery(scrollContainer).offset().top - above
}, speed);}
【讨论】: