Jquery 在新页面加载时滚动到 div

Jquery scroll to div on new page load

我正在尝试实现一个 jQuery 插件来自动向下滚动到新屏幕上的页面, 示例:

www.mysite.com(页眉加载)

www.mysite.com/#div1(页面加载到 div1)

这是我的 jQuery 代码

<script>
    if(window.location.hash) {
        var hash = window.location.hash; //Puts hash in variable
        // hash found
    }
    $(document).ready(function () {
        // Handler for .ready() called.
        $('html, body').animate({ 
            scrollTop: $(hash).offset().top
        }, 2000); 
        alert();
    });
</script>

目前,当我在新屏幕上打开菜单项时,它不会向下滚动。我在 Chrome 控制台上收到此错误:

未捕获的类型错误:无法读取未定义的 属性 'top'

尝试

<script>
    $(document).ready(function () {
        if (location.hash) {
          $('html,body').animate({
            scrollTop: $(location.hash).offset().top
          }, 2000); 
        }       
    });
</script>

如果您有兴趣,可以查看 jquery.localScroll,它可以简化此操作并使页面上的所有链接自动滚动。为此,您需要将 hash 设置设为 true。