更改哈希和动画滚动到元素

时间:2015-07-27 08:11:55

标签: javascript jquery animation hash

我在同一页面上有一个链接和一个元素:

<a href="#about-us" id="link">Click</a>

<div id="#about-us"></div>

以下javascript:

var scrollto = window.location.hash;
if (window.location.hash != null && window.location.hash != '') {
    $('html, body').animate({
        scrollTop: $(scrollto).offset().top
    }, 500);
}

这应该动画滚动到#about-us元素,但它没有,它直接到没有动画的元素,可能是因为不满足哈希条件,尽管url中有一个哈希,因为哈希是在功能之后改变了。

当您单击链接时,我需要一种方法来自动滚动到具有动画的元素。例如,如果这个页面是index.php,你想从另一个page.php转到index.php,直接转到那个元素,它应该加载页面,然后滚动到元素,如果你在index.php但是在页面的顶部,你单击链接,它应该向下滚动到元素。

唯一的问题是当你在同一页面时。它没有通过条件,所以动画不起作用。

更新我已经更改了一些代码。现在条件符合,但动画不起作用..

$('#link').click(function(e) {
    window.location.href='index.php#about-us';
    var scrollto = window.location.hash;
    if (window.location.hash != null && window.location.hash != '') {
        alert(scrollto);
        $('html, body').animate({
            scrollTop: $(scrollto).offset().top
        }, 500);
    }
});

2 个答案:

答案 0 :(得分:1)

这是因为单击链接并调用事件处理程序时未定义window.location.hash

尝试使用:

jQuery(function($) {
    $('#link').on('click', function(e) {
        e.preventDefault();
        var scrollTo = $(this).attr('href'); // retrieve the hash using .attr()

        if (scrollTo != null && scrollTo != '') {
            $('html, body').animate({
                scrollTop: $(scrollTo).offset().top
            }, 500);
        }
    });
});

另外,使用以下命令更改HTML代码:

<div id="about-us"></div> <!-- no need for prepending id value with # -->

See this working JSFiddle

如果要在页面加载时绑定事件,请使用:

$(document).on('load', function(e) { /* the codez */ });

使用var scrollTo = window.location.hash;检索位置哈希,在页面加载时定义。

答案 1 :(得分:0)

此代码适用于我

同一页面滚动的HTML

<a href="#about-us" class="link">Click for About us</a>

<div id="about-us"></div>

外部网页链接的HTML

<a href="product.html#introduction">Click for product introduction</a>

外部页面滚动的HTML

<div id="introduction"></div>

的jQuery

if(window.location.hash){
    var getUrlAfterHash = window.location.hash;
    if($(getUrlAfterHash).length > 0){
        $('html, body').animate({ scrollTop : 0 });
        scrollToTop();
    }
}

$('.link').on('click', function(e){
    e.preventDefault();
    var getUrlAfterHash = $(this).attr('href');
    scrollToTop();
 });

function scrollToTop(){
    var idPositionHeight = $(getUrlAfterHash).offset();
    $('html, body').animate({ scrollTop : idPositionHeight.top}, 800);
}