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

时间:2015-03-20 15:20:45

标签: javascript jquery html scroll

我试图实现一个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控制台上收到此错误:

未捕获的TypeError:无法读取属性&#39; top&#39;未定义的

1 个答案:

答案 0 :(得分:1)

尝试

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

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

相关问题