如果一个元素链接到同一页上的锚点,但当链接到另一个页面上的锚点时,它不会平滑滚动,我的jQuery平滑滚动就能工作。
我的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>发布于 2019-02-26 05:13:08
以下示例代码提供了所需的功能:
$(document).ready(function () {
var urlHash = window.location.href.split("#")[1];
if (urlHash && $('#' + urlHash).length )
$('html,body').animate({
scrollTop: $('#' + urlHash).offset().top - 60
}, 2500);
});请注意,如果URL已经被访问,浏览器将自动跳转到哈希,而不显示动画,然后为了再现我们需要清除缓存的行为,如果我们打算再次显示动画,那么解决方案可能会实现清除缓存功能。
https://stackoverflow.com/questions/54878041
复制相似问题