【问题标题】:Fixed Header Hiding Top of Content固定标题隐藏内容顶部
【发布时间】:2016-02-29 08:00:57
【问题描述】:

我正在开发一个顶部有固定标题的网站。但是,当我导航到锚点时,开始内容被标题隐藏了。有没有更好的方法来抵消我正在使用的代码。我认为这与下面的行有关。整个脚本在下面的小提琴中。

$('a[href^="#"]').on('click', function (e) {
    e.preventDefault();
    $(document).off("scroll");

    $('a').each(function () {
        $(this).removeClass('active');
    })
    $(this).addClass('active');
    var target = this.hash;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 500, 'swing', function () {
        window.location.hash = target;
        $(document).on("scroll", onScroll);
    });
});

https://jsfiddle.net/QuirkCHROMA/d5pp652r/2/

【问题讨论】:

    标签: jquery jquery-animate offset onscroll scroll-position


    【解决方案1】:

    您可以添加您的scrollPosition 和导航栏的高度(80 像素),以便在导航底部到达该部分时更改:

    JS Fiddle

    if (refElement.position().top <= scrollPosition + 80 && refElement.position().top + refElement.height() > scrollPosition + 80 )
    

    对于滚动到部分。减去导航栏的高度:

    $('html, body').stop().animate({
         'scrollTop': $target.offset().top - 80
    }, 500, 'swing', function () {
        window.location.hash = target;
        $(document).on("scroll", onScroll);
    });
    

    缓存高度 - Joseph Marikle 推荐

    您可以做的另一件事是将高度设置为变量,而不是手动将 80 放置在所需的任何位置。这也将允许您更改导航的高度,而无需返回并编辑您的 JS。这样做:

    在加载或调整文档大小时在变量中捕获导航的高度:

    $(window).on('load resize', function () {
        headerHeight = $('header').height();
    });
    

    并在任何可能放置“80”的地方输入该变量名。

    JS Fiddle - With variable

    【讨论】:

    • 我可能会缓存导航高度并在窗口调整大小或其他任何情况下更新它,但否则这是一个不错的可靠解决方案。
    • 好建议。已更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多