Jquery滚动到页面加载

时间:2015-11-04 15:11:45

标签: javascript jquery html css

我试图滚动到网址中的div。它可能是21个ID之一,如:

url.com/test#lite1

url.com/test#lite2

url.com/test#lite3

我需要在页面加载时发生这种情况(用户来自电子书,应该看到他们点击的确切项目)。

以下是我目前的代码:

$(document).ready(function(){
    $('a[href^="#"]').load(function() {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top -150
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

</script>

它没有用,我认为是因为这部分(我不知道我在这做什么):

$('a[href^="#"]').load(function() {

我也希望它位于页面的中心(当滚动到div时,不像浏览器那样顶部切断)。如果这是正确的,请告诉我:

$target.offset().top -150

提前非常感谢!

2 个答案:

答案 0 :(得分:3)

window.location.hash包含URL中的当前哈希值,因此请使用它。由于哈希已经在URL中(正如您所说,他们通过单击带有哈希的链接来到页面),因此您不需要手动添加它。 试试这个:

$(document).ready(function(){
     $('html,body').animate({
          scrollTop: $(window.location.hash).offset().top-150
      }, 900, 'swing');
});

使用wordpress,似乎$需要被jQuery取代,所以它出现在:

jQuery(document).ready(function(){
     jQuery('html,body').animate({
          scrollTop: jQuery(window.location.hash).offset().top-150
      }, 900, 'swing');
});

答案 1 :(得分:0)

作为替代方案,您可以尝试使用以下jQuery插件。我在多个项目中使用过它们。它们可以自定义并提供漂亮,流畅的动画:

scrollTo downloaddocumentation)可让您滚动到页面上的特定元素。基本用法:$(element).scrollTo(target);

localScroll downloaddocumentation)需要scrollTo作为依赖项,并为您处理锚点。您可以通过选择其容器$('#link-container').localScroll();来将其应用于特定的链接集,也可以全局激活它:$.localScroll();

相关问题