Bootstrap 导航栏在滚动时折叠

Mou*_*ing 3 javascript jquery twitter-bootstrap

我在我的项目中使用引导灰度主题,它有一个在滚动时折叠的导航栏,或者如果我转到同一页面上的链接(#download 等)

问题是当我从其他页面转到锚链接时,导航栏在滚动之前不会折叠。

我想解决方案是在java脚本中添加该行,但我真的不知道要添加什么,因为我不知道java。:-(

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".navbar").offset().top > 50) {
    $(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
    $(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
Run Code Online (Sandbox Code Playgroud)

请帮忙。:) :-*

Tim*_*han 5

您需要在页面加载时以及窗口滚动时运行检查,您可以通过将检查页面偏移量的逻辑放入函数中并从文档就绪和窗口运行它来执行此操作,而无需重复任何代码滚动。

$(document).ready(function() {

    // Put your offset checking in a function
    function checkOffset() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar-fixed-top").addClass("top-nav-collapse");
        }     
        else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
        }
    }

    // Run it when the page loads
    checkOffset();


    // Run function when scrolling
    $(window).scroll(function() {
        checkOffset();
    });
});
Run Code Online (Sandbox Code Playgroud)

编辑:

我相信您可以通过将 checkOffset 函数替换为以下内容来进一步缩短此时间:

// Put your offset checking in a function
function checkOffset() {
    $(".navbar-fixed-top").toggleClass("top-nav-collapse", $(".navbar").offset().top > 50);
}
Run Code Online (Sandbox Code Playgroud)

我还没有测试过这一点,但只要toggleClass中的第二个参数返回一个布尔值,它就会根据页面的偏移量添加或删除类,而不需要if语句。