Py学习  »  Jquery

jQuery在不同页面上平滑滚动以定位

James Leavitt • 5 年前 • 326 次点击  

如果一个元素链接到同一页上的锚定,那么jQuery smooth scroll可以工作,但是当链接到另一页上的锚定时,它不会平滑滚动。

我的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>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52197
 
326 次点击  
文章 [ 1 ]  |  最新文章 5 年前
YPCA
Reply   •   1 楼
YPCA    5 年前

下面的示例代码似乎运行良好。 除此之外,如果URL已经加载,它将只滚动到没有动画的散列,然后通过点击(Shift+F5)或(Ctrl+F5)在没有缓存的情况下重新加载页面,它将按照预期再次工作。可以通过实现清除缓存函数来解决此问题。

$(document).ready(function () {
    var urlHash = window.location.href.split("#")[1];
    if (urlHash &&  $('#' + urlHash).length )
          $('html,body').animate({
              scrollTop: $('#' + urlHash).offset().top - 60
          }, 2500);
});