Bootstrap导航栏在滚动时崩溃 [英] Bootstrap navbar collapse on scroll

查看:86
本文介绍了Bootstrap导航栏在滚动时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using bootstrap grayscale theme for my project and It has a navbar that collapses on scroll, or if I go to a link that's on the same page (#download etc.)

问题是当我从其他页面锚定链接时,导航栏直到我滚动才折叠.

The problem is when I go to anchor link from some other page, than navbar doesn't collapse until I scroll.

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

I guess the solution is in adding the line in java script, but I really don't know what to add since I don't know 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");
}
});

请帮忙. :):-*

Please, help. :) :-*

推荐答案

您需要在加载页面以及滚动窗口时运行检查,而无需通过放置检查逻辑来重复任何代码来执行检查页面在函数中的偏移量,并从文档就绪状态和窗口滚动状态开始运行.

You need to run the check when the page loads as well as when the window is scrolled, you can do that without duplicating any code by putting the logic that checks the offset of the page in a function and running it from both document ready and window scroll.

$(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();
    });
});

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

I believe you could shorten this even more by replace the checkOffset function with the following:

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

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

I haven't tested this, but as long as the second parameter in toggleClass returns a boolean it'll either add or remove the class depending on the offset of the page without needing an if statement.

这篇关于Bootstrap导航栏在滚动时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆