jquery - 带有偏移量的 Jquery 平滑滚动
问题描述
我的网站上有以下用于平滑滚动的代码。现在,当我单击以移动到新部分时,它会切断该部分的标题。我已经看到其他显示偏移量的 jquery 示例,但我想修改此代码,因为它现在不在我的站点上工作。
$(document).ready(function () {
$("a").on("click", function (event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$("html, body").animate(
{
scrollTop: $(hash).offset().top,
},
800,
function () {
window.location.hash = hash;
}
);
}
});
});
解决方案
当您将部分的顶部设置为 时scrollTop
,它将滚动直到该部分位于视口的开头,如下所示。
但是您可以记住,您的网站顶部有一个粘性标题。因此,需要通过从部分顶部删除该空间来保留该空间。
$(document).ready(function () {
$("a").on("click", function (event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$("html, body").animate(
{
scrollTop: $(hash).offset().top - 109, // section's top - header's height
},
800,
function () {
window.location.hash = hash;
}
);
}
});
});
如果您需要进一步的支持,请告诉我。
推荐阅读
- c++ - 为什么指向类数组的全局指针与本地指针不同?
- javascript - JavaScript 铬自动化
- spring - 使用spring boot部署新版本时如何触发升级服务?
- google-sheets - 将一行转换为固定数量的多行和多列 Google 表格
- jquery - jQuery - 结帐过程触发点击
- react-native - 在反应本机选项卡导航中将指示器边框应用于选定选项卡
- c# - 如何从 Blazor Server 中的页面处置(销毁)组件?
- python - 如何使用 python alpha_vantage API 返回扩展的日内数据?
- io - 一个时间段内可以发生多少个 I/O 中断?
- swiftui - SwiftUI 自动字符串本地化问题