【问题标题】:Highlighting current section in navbar在导航栏中突出显示当前部分
【发布时间】:2016-03-21 09:27:02
【问题描述】:

我有一个带有导航栏的滚动页面,我希望用户滚动浏览的部分在导航栏中突出显示。目前它几乎完成了这一点,但突出显示了不正确的链接。

演示在http://codepen.io/meek/pen/NNprYb?editors=1000

执行此操作的代码如下:

// highlight current tab
    $(window).on("scroll", function() {

        var currentPos = $(window).scrollTop();

        $('.nav li a').each(function() {
            var sectionLink = $(this);
            var section = $(sectionLink.attr('href'));
            if(section.position().top <= currentPos && sectionLink.offset().top + section.height() >= currentPos) {
                $('.nav li').removeClass('active');
                sectionLink.parent().addClass('active');
            }
            else {
                sectionLink.parent().removeClass('active');
            }
        });

    });

我尝试了几件事,但无法将活动类可靠地添加到正确的会话中。感谢您的帮助!

编辑:为了更清楚,问题在于它仅在您滚动一点时突出显示该部分,而不是在顶部,这意味着当您单击一个部分以滚动到该部分的顶部时自动,该部分不会突出显示。

edit2:所以将 if 语句更改为:

if(currentPos + $('#nav-wrapper').outerHeight() >= section.position().top && currentPos + $('#nav-wrapper').outerHeight() <= sectionLink.offset().top + section.outerHeight()) {

虽然没有完全解决问题,但已经有所改进。主页、关于和投资组合部分都突出显示正确的链接,但没有显示联系方式。

【问题讨论】:

    标签: javascript jquery twitter-bootstrap


    【解决方案1】:

    您需要考虑导航栏的高度,并从要突出显示的部分的顶部减去它。

    高度目前在您的 CSS 中硬编码为 75 像素,但我为高度添加了一个 jQuery 选择器,以防它需要在较小的屏幕上更改/消失。

    顺便说一句,干得好。

    $(window).on("scroll", function() {
      var currentPos = $(window).scrollTop();
    
      $('.nav li a').each(function() {
        var sectionLink = $(this);
        // capture the height of the navbar
        var navHeight = $('#nav-wrapper').outerHeight() + 1;
        var section = $(sectionLink.attr('href'));
    
        // subtract the navbar height from the top of the section
        if(section.position().top - navHeight  <= currentPos && sectionLink.offset().top + section.height()> currentPos) {
          $('.nav li').removeClass('active');
          sectionLink.parent().addClass('active');
        } else {
          sectionLink.parent().removeClass('active');
        }
      });        
    });
    

    【讨论】:

    • 非常感谢您的帮助和客气话,但由于某种原因,“联系人”部分仍未突出显示。你知道为什么会这样吗?
    • 啊,更改 navHeight 选择器以选择 nav-wrapper id。差异是几个像素的问题,可能是由一些轻微的 div 填充引起的。编辑在我的回答中!
    • 准确地说,$('#navbar-wrapper') 的高度是 70px,$('.navbar.navbar-default.navbar-static-top.affix') 是 69px。因此,1px 的差异阻止了逻辑将活动状态添加到联系链接。
    • 我试过了,但还是一样。奇怪的是,if 语句中的 section.position().top - navHeight - 1 却可以正常工作,尽管这感觉不是完全正确的方法。扔掉它只有一个像素
    • 试试navHeight = $('#nav-wrapper').outerHeight() + 1
    猜你喜欢
    • 2017-01-31
    • 1970-01-01
    • 2015-08-23
    • 2021-06-19
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    相关资源
    最近更新 更多