缓慢导航至 URL 中的 id

问题描述 投票:0回答:2

在我的主页上有一个带有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');
}

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

javascript jquery url jquery-animate
2个回答
1
投票

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

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

另外,删除 e.preventDefault(),因为您没有定义任何名为

e
event
的变量。


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 中,并在页面的头部检查它是否已设置。

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

© www.soinside.com 2019 - 2024. All rights reserved.