【发布时间】:2021-10-25 21:51:19
【问题描述】:
当我们单击导航菜单项时,我正在使用以下代码平滑滚动到部分:
// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
// target element id
var id = $(this).attr('href');
// target element
var $id = $(id);
if ($id.length === 0) {
return;
}
// prevent standard hash navigation (avoid blinking in IE)
e.preventDefault();
// top position relative to the document
var pos = $id.offset().top;
// animated top scrolling
$('body, html').animate({scrollTop: pos}, 2000);
});
但是,我需要将标题放置在固定位置,高度为 90 像素,现在当我们滚动到该部分时,该部分的开头隐藏在该部分后面。 是否可以保留我的代码并包括例如与顶部的一定距离?
我尝试在offset方法上放一个参数,但是没有成功:
// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
// target element id
var id = $(this).attr('href');
// target element
var $id = $(id);
if ($id.length === 0) {
return;
}
// prevent standard hash navigation (avoid blinking in IE)
e.preventDefault();
// top position relative to the document
var pos = $id.offset(top:120).top;
// animated top scrolling
$('body, html').animate({scrollTop: pos}, 2000);
});
我做错了吗?
【问题讨论】:
标签: javascript jquery animation scroll