【发布时间】:2022-01-18 02:13:46
【问题描述】:
我有一些很长的页面。在页脚中,我有一个锚链接将用户带回页眉。我希望能够使用以下 CSS(但它在 Safari 中不起作用)来使滚动平滑(放慢速度)。
html {
scroll-behavior: smooth;
}
所以我找到了一些 JQuery。我不懂 JQuery,有一些问题。
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
- 是否有可能使这更简单?
2.我不确定是否需要将#top 添加到 URL 中?我想要页面做的就是回到顶部(我没有使用锚链接来导航到内容位)。但我不知道如何在不破坏整个内容的情况下删除此代码。我试过了,不知道要删除什么,要保留什么。
- 这是什么意思“确保 this.hash 有一个值”。我忽略了它,它似乎工作正常。
更新
这是我的 HTML(显然页眉和页脚之间有很多内容)
<header id="top">.... </header>
<footer>
<a href="#top"><img class="to-top" src="resources/arrow.svg"></a>
</footer>
【问题讨论】:
-
我的意思是,完全删除 jquery 并依赖 css,会更简单,不是吗?
-
CSS 在 Safari 中不起作用,请参阅帖子
-
没关系。这不是必需的功能。
-
我需要滚动平滑,而不是立即滚动。所以这是必要的。
标签: javascript html jquery