如果一个元素链接到同一页面上的 anchor ,我的 jQuery 平滑滚动可以工作,但当链接到不同页面上的 anchor 时,它不会平滑滚动。
我的 jQuery 脚本有任何明显的问题吗?
<script>
jQuery(function($) {
// //////////////////////// Smooth Scroll To Specific Element On Page ////////////////////////
$(document).ready(function() {
$('a[href^="#"]').not('.carousel-control-prev').not('.carousel-control-next').bind('click.smoothscroll', function(e) {
e.preventDefault();
var hash = this.hash;
jQuery('html, body').animate({
scrollTop: jQuery(hash).offset().top - 65
}, 1500, function(){});
});
});
//////////////////////// Smooth Scroll To Specific Element On Different Page ////////////////////////
$(document).ready(function(){
var urlHash = window.location.href.split("#")[1] || false;
if (urlHash.length > 0)
$('html,body').animate({
scrollTop: $('#' + urlHash).offset().top - 60
}, 2500);
});
});
</script>
最佳答案
以下示例代码提供了所需的功能:
$(document).ready(function () {
var urlHash = window.location.href.split("#")[1];
if (urlHash && $('#' + urlHash).length )
$('html,body').animate({
scrollTop: $('#' + urlHash).offset().top - 60
}, 2500);
});
请注意,如果该 URL 已被访问,浏览器将自动跳转到哈希而不显示动画,然后要重现我们需要清除缓存的行为,那么解决方法可以是实现清除缓存功能,如果我们打算再次显示动画。
关于javascript - jQuery 平滑滚动以锚定在不同页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54878041/