在URL中缓慢导航到id

时间:2013-04-12 01:51:24

标签: javascript jquery url jquery-animate

在我的主页上,我有一个带有ID的菜单,当我点击它时,它会滑动到相应的div,它可以实现平滑。

但是当我不在我的主页上并点击某个项目时,我希望能够转到主页,然后滑到该部分。

以下是我现在使用的代码:

$('#mainMenu a').click(function(e){
    e.preventDefault();
    var div = $(this).attr('href');
    if('<?=get_site_url()?>/' == '<?=get_permalink()?>')
    {
        $('html, body').animate({scrollTop:$(div).position().top}, 'slow');
    }
    else
    {
        window.location.href = '<?=get_site_url()?>/'+div;
    }
});

这很好用,下一部分适用但我无法将其滑入ID。

if (window.location.hash != "") {
    e.preventDefault();
    $('html, body').animate({scrollTop:$(window.location.hash).position().top}, 'slow');
}

有没有办法阻止浏览器直接跳转到该部分,而是滑向它?

2 个答案:

答案 0 :(得分:1)

尝试在开始时滚动到右上角,然后向下滚动:

if (window.location.hash != "") {
    $('html, body').scrollTop(0).animate({scrollTop:$(window.location.hash).position().top}, 'slow');
}

此外,删除e.preventDefault(),因为您没有定义任何名为e的变量,也没有定义event

答案 1 :(得分:0)

这就像一个魅力:

$('#mainMenu a').click(function(e){
    e.preventDefault();
    var div = $(this).attr('href');
    if('<?=get_site_url()?>/' == '<?=get_permalink()?>')
    {
        $('html, body').animate({scrollTop:$(div).position().top}, 'slow');
    }
    else
    {
        localStorage.setItem("hash", div);
        window.location.href = '<?=get_site_url()?>/';
    }
});

if (localStorage.getItem("hash")!=null) {
    $('html, body').animate({scrollTop:$(localStorage.getItem("hash")).position().top}, 'slow');
    localStorage.removeItem("hash");
}

我没有将哈希值放在我的网址中,而是将其存储在localStorage中,在页面的头部,我检查了它是否已设置。

在发布问题后几分钟就建立了这个解决方案,感谢那些帮助过我的人:)

相关问题