jQuery平滑滚动到相同页面和其他页面上的ID:如何设置偏移量

jQuery Smooth Scroll to ID on same and on other page: how to set offset?

本文关键字:何设置 偏移量 设置 ID 滚动 平滑 jQuery 其他      更新时间:2024-03-01

我在页面上使用jQuery跳转/滚动到ID。

这适用于其他具有等锚点的页面

<a href="other-page.php#jump-id">Jump & Scroll to ID on other page</a>

并且在同一页面上,只有像这样的锚点

<a href="#jump-id">Jump / Scroll to ID on the same page</a>

这不是最好的解决方案,因为我必须更改导航菜单,但它有效(我在页面上加载另一个带有其他标签的菜单)。

现在我正在寻找一种方法,将-230px的偏移量添加到滚动/跳转脚本中,因为我的页面上有一个固定的页眉

我认为这很简单,但不幸的是,我不是jQuery专业人士。我该怎么做?请帮助我将-230偏移添加到此功能:)

jQuery代码:

(function($){
    var jump=function(e)
    {
       if (e){
           e.preventDefault();
           var target = $(this).attr("href");
       }else{
           var target = location.hash;
       }
       $('html,body').animate(
       {
           scrollTop: $(target).offset().top
       },1000,function()
       {
           location.hash = target;
       });
    }
    $('html, body').hide()
    $(document).ready(function()
    {
        $('a[href^=#]').bind("click", jump);
        if (location.hash){
            setTimeout(function(){
                $('html, body').scrollTop(0).show()
                jump()
            }, 0);
        }else{
          $('html, body').show()
        }
    });
})(jQuery)

负责说明页面将向下滚动多少的是scrollTop: $(target).offset().top,因此,如果您想偏移-230px,只需从$(target).offset().top中减去230

但是,如果您在当前代码中这样做,它将不起作用,因为您正在使用location.hash = target;更改哈希。当你这样做时,你的浏览器会找到哈希并跳转到它(不设置动画,只是跳转)。

观察此演示:http://jsfiddle.net/pcyn2fvk/

如果单击锚点,页面将向下滚动到内容,滚动后将跳转(这是由location.hash = target;引起的)。

以下是未使用location.hash = target;的演示:http://jsfiddle.net/pcyn2fvk/1/

我想你需要更改哈希,所以,你可以尝试一种不同的方法,比如Lea Verou解释的方法(http://lea.verou.me/2011/05/change-url-hash-without-page-jump/)其使用历史API而不是CCD_ 8。

还有一些其他方法,例如,当您单击锚点时,您可以删除目标节(您单击以滚动到的节)的id,然后,当您使用location.hash更改位置时,浏览器将找不到单击的id,也不会跳转到它,然后,您可以将id重新分配给您的节。

希望它能有所帮助!

我发现了另一种使用锚点标签的方法。这允许我加载一个不同的页面,并滚动到带有偏移量的id。

在IE中,滚动在所有页面上都能很好地工作,但所有其他浏览器都不会在smae页面上滚动。如果我点击我想滚动的页面上的链接,他们会跳到hastags,而不使用我的jQuery滚动功能。如果我从其他URL点击同一个链接,滚动就会工作。

(其他方法,仅适用于<a href="page-b.php#anchor">Link on Page A to Page B</a>

$(document).ready(function() {
    $('html, body').hide();
    if (window.location.hash) {
        setTimeout(function() {
            $('html, body').scrollTop(0).show();
            $('html, body').animate({
                scrollTop: $(window.location.hash).offset().top -230
                }, 1000)
        }, 0);
    }
    else {
        $('html, body').show();
    }
});