【问题标题】:Jquery scrolltop offsetting fixed headerJquery scrolltop 偏移固定标头
【发布时间】:2011-10-27 12:07:28
【问题描述】:

我正在使用 JQuery 来平滑滚动图像:

function smoothScrollTo(hash) {
    $("html:not(:animated).,body:not(:animated)").animate({
        scrollTop: $(hash).offset().top
    }, 650, function () {
        location.hash = hash;
    });
}
$(function () {
    $("#content-images li a[href*=#]").click(function () {
        this.blur();
        smoothScrollTo(this.hash);
        return false;
    });
});

它工作正常,但是我在网站上有一个固定的导航栏,它在滚动时停留在页面的顶部。当页面向下滚动到下一个图像时,它会在导航栏下方滚动,从而遮挡视线。

我的问题是,如何修改上面的代码来补偿我的固定导航栏的高度?

任何帮助将不胜感激,

T

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    变化:

    scrollTop: $(hash).offset().top
    

    到:

    scrollTop: $(hash).offset().top + $('#fixed_nav_bar').outerHeight()
    

    这应该考虑到固定的导航栏高度。

    希望有帮助:)

    【讨论】:

    • 非常感谢!它确实有效,但是现在似乎发生的是,它向下平滑滚动,然后一旦到达元素,它将迅速偏移高度,导致页面跳到正确的位置,从而不再使其非常平滑。有解决办法吗?
    • 那是因为动画回调改变了location.hash,和点击链接一样。给我一秒钟,我最近不得不处理这个问题。 编辑:实际上,这行不通,但是,试试这个:stackoverflow.com/questions/1489624/…
    • 谢谢!已阅读并且似乎无法使其正常工作,它只会产生一个错误,您在单击图像后无法再向下滚动。有没有办法在这种情况下只删除 location.hash 回调?
    【解决方案2】:

    使用 will 的答案,试试这个:

    function smoothScrollTo(hash, t) { // two params
        $("html:not(:animated).,body:not(:animated)").animate({
            scrollTop: $(hash).offset().top + $('#fixed_nav_bar').outerHeight()
        }, 650, function () {
            var tmp = t.id; // hold the id
            t.id = '';      // remove it so we don't jump
            location.hash = hash;
            t.id = tmp;     // now that we didn't jump we can move it back
        });
    }
    $(function () {
        $("#content-images li a[href*=#]").click(function () {
            this.blur();
            smoothScrollTo(this.hash, this); // two args
            return false;
        });
    });
    

    【讨论】:

    • 非常感谢!刚刚对其进行了测试并对您的代码和遗嘱进行了进一步的观察,似乎它只是没有考虑标题高度。图像仍然滚动到浏览器窗口的顶部(固定导航下方)有没有办法让我手动设置高度?
    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多