html - 如何让 Bootstrap 固定导航栏不是全宽,顶部有横幅

标签 html css twitter-bootstrap

所以我才刚刚开始使用 Bootstrap ,我需要设置导航栏的帮助。

理想情况下,我想要的是有一个顶部居中的横幅,并且在其正下方有一个导航栏。当用户向下滚动时,横幅将滚动到屏幕外,但导航栏将固定在顶部。如果用户再次向上滚动,横幅将重新出现。对于移动用户,他们会在右侧看到图标,按下时会创建一个下拉菜单。

横幅和顶部导航栏不是全宽的。横幅长 960 像素,我使用 class="col-xs-12 col-md-10 col-md-offset-1" 进行设置。从美学上讲,它对我来说看起来不错。

我看过一些关于这个主题的帖子,但没有一个真正将所有这些要求混合在一起(不是全宽、坚持顶部和导航栏顶部的横幅标志)。我尝试了一些方法的逆向工程,但我一点运气都没有。

目前,我只使用药盒,因为它对我来说很容易制作和格式化。任何帮助是极大的赞赏。谢谢!

更新:这是我目前拥有的代码。我对这个设置很满意,只是希望导航栏在向下滚动后保持不变。正如您将看到的,这里有很多 div,我用它们来设置页面和阴影的样式。可能会更有效率,但它看起来完全符合我的要求。

HTML:

<div class="container-fluid">
    <div class="row">
        <div class="col-xs-12 col-md-10 col-md-offset-1 rcshadow">
            <div class="row">
                <img class="img-responsive center-block" src="../images/header.jpg">
                <!-- Fixed navbar -->
                <div class="navbar navbar-default navbar-rc">
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        <a class="navbar-brand" href="#"><span class="glyphicon glyphicon-home" /></span>&nbsp;Roll Call</a>
                    </div>
                    <div class="collapse navbar-collapse">
                        <ul class="nav navbar-nav">
                            <li><a href="#"><span class="glyphicon glyphicon-user">&nbsp;New</span> <span class="glyphicon">Contact</span></a></li>
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-search" />&nbsp;Search<b class="caret"></b></a>
                                <ul class="dropdown-menu">
                                    <li><a href="#">Contact Search</a></li>
                                    <li class="divider"></li>
                                    <li class="dropdown-header">Quick Search</li>
                                    <li><a href="#">
                                            <form class="navbar-form" role="search">
                                                <div class="input-group input-group-xs">
                                                    <input type="text" class="input" placeholder="Search by name..." name="srch-term" id="srch-term">
                                                    <div class="btn-group btn-group-xs">
                                                        <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
                                                    </div>
                                                </div>
                                            </form>                                        
                                    </a></li>
                                </ul>
                            </li>
                            <li><a href="#contact"><span class="glyphicon glyphicon-list-alt" />&nbsp;Attendance</a></li>
                            <li><a href="#contact"><span class="glyphicon glyphicon-calendar" />&nbsp;Planner</a></li>
                            <li><a href="#contact"><span class="glyphicon glyphicon-stats" />&nbsp;Statistics</a></li>
                        </ul>
                        <ul class="nav navbar-nav navbar-right">
                            <li><a href="#contact"><span class="glyphicon glyphicon-log-out" />&nbsp;Log-out</a></li>
                        </ul>
                    </div><!--/.nav-collapse -->
                </div>
            </div>
            <div class="row">
                <div class="rcpage">
                    <div class="row">
                        <h1>Test</h1>
                        <hr>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

我的 css 文件(除了 Bootstrap ):

/* set a max-width for horizontal fluid layout and make it centered */
.container-fluid {
  margin-right: auto;
  margin-left: auto;
  max-width: 970px;
}

body {
    margin:0;
    padding:0;
    font-size:100%;
    font-family:verdana,arial,'sans serif';
    background-color:#3b607e;
    color:#000000;
}

.navbar-rc {
    margin-bottom:0px;
    -moz-border-radius:0px;
    border-radius:0px;
}

.navbar-nav > li > a, .navbar-brand {
    padding-top:5px !important; 
    padding-bottom:0 !important; 
    height: 30px; 
} 

.navbar-nav > li:hover, .navbar-header:hover {
    background-color:#e7e7e7;   
}

.navbar {
    min-height:30px !important;
}

.rcshadow {
    -moz-box-shadow: 0px 0px 30px 10px #000;
    -webkit-box-shadow: 0px 0px 30px 10px #000;
    -khtml-box-shadow: 0px 0px 30px 10px #000;
    box-shadow: 0px 0px 30px 10px #000;
    -moz-border-radius: 0px 0px 15px 15px;
    border-radius: 0px 0px 15px 15px;
}

.rcpage {
    background-color:#FFF;
    padding:0px 30px;
    margin-left:auto;
    margin-right:auto;
    -moz-border-radius: 0px 0px 15px 15px;
    border-radius: 0px 0px 15px 15px;
}

最佳答案

当您滚动到正确的位置时,您可以调整导航栏以使其position: fixed。但是,这会使其在 DOM 中失去位置,因此您需要调整宽度和位置,并通过向容器元素添加边距来弥补丢失的空间。您可能需要考虑其他一些事情,例如像 bootstrap 通常使用 navbar-fixed-top 那样去掉 border-radius。仅添加该类而不是设置 position:fixed 实际上可能更好,但我在示例中遇到了一些其他问题,因此需要进行一些调整。

这里有一些额外的 javascript 来检查横幅高度,而不是根据它应该的高度对其进行硬编码。它只检查页面何时调整大小,但这可能需要进一步调整(例如,如果您在页面上动态添加元素,它可能会影响栏的高度,或者如果将滚动条添加到页面以解决溢出问题) .

我将 id 添加到导航栏的关键部分,但您也可以通过其他方式获得它们(例如,如果您只有一个导航栏,您可以只使用 .navbar

我将 id="banner" 添加到您的横幅,并将 id="navbar-container" 添加到包含它的 div(也包含导航栏)。我将 id="navbar" 添加到具有 .navbar 类的元素。

然后,这里是 javascript 的简化版本,只是为了显示重要的部分。不过,我已经对其进行了一些优化,您可以在完整的代码片段中看到这一点。由于某种原因,宽度似乎偏离了一个像素;我并没有真正深入研究为什么会这样,只是在设置宽度时将其添加回去。

$(document).on("scroll", function () {
    var bannerHeight = $("#banner").outerHeight(true),
        shouldBeSticky = $(window).scrollTop() > bannerHeight,
        $container = $("#navbar-container"),
        $navbar = $("#navbar");

      if (shouldBeSticky) {
        var margin = parseInt($container.css("margin-bottom"), 10);
        $container.css("margin-bottom", margin + $navbar.outerHeight(true) + "px");
        $navbar.css({
          width: $navbar.outerWidth(true) + 1 + "px",
          left: $navbar.offset().left + "px",
          top: 0,
          position: "fixed"
        })
      } else {
        $container.css("margin-bottom", "");
        $navbar.css({
          width: "",
          left: "",
          top: "",
          position: ""
        });
      }
    }
  }
});

jQuery(function($) {
  var bannerHeight = 0,
    navbarHeight = 0,
    scrollTop = 0,
    isSticky = false,
    $container = $("#navbar-container"),
    $navbar = $("#navbar"),
    $banner = $("#banner"),
    $window = $(window);

  function setHeights() {
    bannerHeight = $banner.outerHeight(true);
    navbarHeight = $navbar.outerHeight(true);
  }

  function setScrollTop() {
    scrollTop = $window.scrollTop();
  }

  function affixScrollbar() {
    if (!bannerHeight || !navbarHeight) setHeights();

    var shouldBeSticky = scrollTop > bannerHeight;
    if (shouldBeSticky !== isSticky) {
      if (isSticky = shouldBeSticky) {
        var margin = parseInt($container.css("margin-bottom"), 10),
          width = $navbar.outerWidth(true) + 1 + "px",
          left = $navbar.offset().left + "px";
        $container.css("margin-bottom", margin + navbarHeight + "px");
        $navbar.css({ width: width, left: left, top: 0, position: "fixed" });
      } else {
        $container.css("margin-bottom", "");
        $navbar.css({ width: "", left: "", top: "", position: "" });
      }
    }
  }

  $(window).on("resize", function() {
    setHeights();
    affixScrollbar();
  });

  $(document).on("scroll", function() {
    setScrollTop();
    affixScrollbar();
  });

  setHeights();
  setScrollTop();
  affixScrollbar();
});
/* set a max-width for horizontal fluid layout and make it centered */

.container-fluid {
  margin-right: auto;
  margin-left: auto;
  max-width: 970px;
}
body {
  margin: 0;
  padding: 0;
  font-size: 100%;
  font-family: verdana, arial, 'sans serif';
  background-color: #3b607e;
  color: #000000;
}
.navbar-rc {
  margin-bottom: 0px;
  -moz-border-radius: 0px;
  border-radius: 0px;
}
.navbar-nav > li > a,
.navbar-brand {
  padding-top: 5px !important;
  padding-bottom: 0 !important;
  height: 30px;
}
.navbar-nav > li:hover,
.navbar-header:hover {
  background-color: #e7e7e7;
}
.navbar {
  min-height: 30px !important;
}
.rcshadow {
  -moz-box-shadow: 0px 0px 30px 10px #000;
  -webkit-box-shadow: 0px 0px 30px 10px #000;
  -khtml-box-shadow: 0px 0px 30px 10px #000;
  box-shadow: 0px 0px 30px 10px #000;
  -moz-border-radius: 0px 0px 15px 15px;
  border-radius: 0px 0px 15px 15px;
}
.rcpage {
  background-color: #FFF;
  padding: 0px 30px;
  margin-left: auto;
  margin-right: auto;
  -moz-border-radius: 0px 0px 15px 15px;
  border-radius: 0px 0px 15px 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />


<div class="container-fluid">
  <div class="row">
    <div class="col-xs-12 col-md-10 col-md-offset-1 rcshadow">
      <div class="row" id="navbar-container">
        <img class="img-responsive center-block" src="../images/header.jpg" id="banner">
        <!-- Fixed navbar -->
        <div class="navbar navbar-default navbar-rc" id="navbar">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#"><span class="glyphicon glyphicon-home" /></span>&nbsp;Roll Call</a>
          </div>
          <div class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
              <li><a href="#"><span class="glyphicon glyphicon-user">&nbsp;New</span> <span class="glyphicon">Contact</span></a>
              </li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-search" />&nbsp;Search<b class="caret"></b>
                </a>
                <ul class="dropdown-menu">
                  <li><a href="#">Contact Search</a>
                  </li>
                  <li class="divider"></li>
                  <li class="dropdown-header">Quick Search</li>
                  <li>
                    <a href="#">
                      <form class="navbar-form" role="search">
                        <div class="input-group input-group-xs">
                          <input type="text" class="input" placeholder="Search by name..." name="srch-term" id="srch-term">
                          <div class="btn-group btn-group-xs">
                            <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i>
                            </button>
                          </div>
                        </div>
                      </form>
                    </a>
                  </li>
                </ul>
              </li>
              <li>
                <a href="#contact"><span class="glyphicon glyphicon-list-alt" />&nbsp;Attendance</a>
              </li>
              <li>
                <a href="#contact"><span class="glyphicon glyphicon-calendar" />&nbsp;Planner</a>
              </li>
              <li>
                <a href="#contact"><span class="glyphicon glyphicon-stats" />&nbsp;Statistics</a>
              </li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
              <li>
                <a href="#contact"><span class="glyphicon glyphicon-log-out" />&nbsp;Log-out</a>
              </li>
            </ul>
          </div>
          <!--/.nav-collapse -->
        </div>
      </div>
      <div class="row">
        <div class="rcpage">
          <div class="row">
            <h1>Test</h1>
            <hr>
          </div>
          <p>Retro iPhone four dollar toast, synth Schlitz Austin cray typewriter Thundercats fashion axe fixie aesthetic bicycle rights. Bicycle rights taxidermy pickled tattooed. Kogi shabby chic Tumblr, Helvetica American Apparel raw denim chia before
            they sold out aesthetic bicycle rights taxidermy salvia paleo. Skateboard bespoke fanny pack, Godard hashtag put a bird on it yr vinyl sustainable tofu photo booth meh Thundercats forage. Street art 90's skateboard sartorial synth McSweeney's.
            Cornhole High Life twee tote bag, polaroid Pinterest listicle literally organic sartorial YOLO blog master cleanse 8-bit. Small batch Banksy wolf yr.</p>
          <p>Aesthetic cornhole lo-fi plaid, Odd Future seitan blog paleo. Ugh cronut aesthetic whatever photo booth PBR. Carles pop-up XOXO +1 readymade, meh health goth DIY. Chillwave Pitchfork kogi, Echo Park quinoa meggings fap asymmetrical Austin Wes
            Anderson butcher Neutra hella PBR mixtape. IPhone Bushwick wayfarers, organic ennui ethical flexitarian. Blue Bottle 8-bit single-origin coffee hashtag, Marfa mlkshk meggings literally pug YOLO. Small batch cliche literally, lumbersexual try-hard
            beard whatever Etsy umami skateboard tote bag Pitchfork.</p>
          <p>Street art YOLO scenester, irony tousled shabby chic crucifix roof party bitters gastropub you probably haven't heard of them. Keffiyeh before they sold out wolf typewriter DIY Thundercats. Keffiyeh banh mi meditation pug, leggings 3 wolf moon
            sriracha Blue Bottle. Swag ennui biodiesel, fashion axe mumblecore lomo sustainable lumbersexual American Apparel narwhal tofu Helvetica kitsch cred +1. Cronut squid keytar retro, chillwave ugh authentic synth semiotics distillery fingerstache
            bespoke Williamsburg. Helvetica chambray tote bag semiotics Godard fingerstache. Actually slow-carb artisan blog, deep v tote bag keytar pickled lomo Pitchfork biodiesel.</p>
          <p>Ethical Etsy drinking vinegar PBR&B Echo Park direct trade. Pug cronut ethical, you probably haven't heard of them Helvetica tousled mumblecore flexitarian before they sold out YOLO PBR&B dreamcatcher. XOXO craft beer sriracha, hella PBR&B polaroid
            Brooklyn Williamsburg banh mi biodiesel cray bicycle rights typewriter. Brunch vegan tousled, leggings hella chia deep v cold-pressed VHS. Jean shorts post-ironic authentic literally Shoreditch squid. Polaroid mixtape freegan, food truck Blue
            Bottle 90's umami. Craft beer Blue Bottle cliche, banjo polaroid keytar put a bird on it chillwave 90's.</p>
          <p>Four loko keffiyeh migas, kitsch High Life DIY chillwave farm-to-table banh mi gluten-free mixtape locavore. Flexitarian paleo photo booth fap, scenester mustache High Life organic small batch. Pug raw denim organic, biodiesel bicycle rights
            keytar mustache art party gentrify fingerstache ennui Williamsburg craft beer Brooklyn. Letterpress sustainable kogi squid cornhole. Semiotics disrupt pickled, kitsch XOXO scenester skateboard lumbersexual sustainable food truck pork belly
            crucifix Godard raw denim fixie. Pour-over master cleanse forage VHS, Thundercats disrupt pug Truffaut vegan quinoa keffiyeh Echo Park cardigan you probably haven't heard of them. Mumblecore leggings iPhone Blue Bottle, fashion axe street
            art chia Godard distillery shabby chic.</p>
          <p>Flexitarian Kickstarter migas, distillery jean shorts roof party cold-pressed lumbersexual. Asymmetrical 3 wolf moon Truffaut, Wes Anderson lo-fi hashtag PBR&B tousled Schlitz hoodie pug Williamsburg. American Apparel skateboard chambray Wes
            Anderson. Echo Park 90's Pitchfork Portland street art pop-up, flannel banh mi Godard VHS literally food truck. Semiotics butcher farm-to-table Etsy church-key Schlitz, tousled XOXO Vice street art selfies lumbersexual locavore. Cronut yr
            post-ironic plaid pop-up tattooed DIY master cleanse paleo, normcore scenester quinoa slow-carb. Neutra wolf jean shorts umami banjo fashion axe.</p>
          <p>Dreamcatcher migas artisan, iPhone tofu Austin food truck forage four dollar toast organic four loko gentrify Portland trust fund. Irony tilde mlkshk Neutra, gentrify organic pop-up next level photo booth. Austin Godard keffiyeh, plaid Tumblr
            vinyl meditation freegan direct trade mustache. Actually yr polaroid flexitarian banh mi. Sartorial cray Blue Bottle cred. Gluten-free YOLO post-ironic, craft beer Kickstarter American Apparel freegan. Marfa meggings tote bag biodiesel, umami
            migas kogi photo booth letterpress single-origin coffee Bushwick. Deep v organic readymade hashtag. Plaid mustache wolf irony leggings. Tilde occupy sustainable synth irony, readymade wolf normcore put a bird on it cliche. Cray fap cronut
            butcher, trust fund umami banh mi. Street art retro next level forage. Kogi fashion axe sriracha, biodiesel ugh cray roof party. Kogi keffiyeh occupy paleo bicycle rights, drinking vinegar tousled Portland.</p>
          <p>You probably haven't heard of them fanny pack street art pour-over, Wes Anderson 8-bit chambray mustache pork belly drinking vinegar. Bushwick health goth mumblecore keytar. 3 wolf moon direct trade put a bird on it twee tousled deep v, kogi
            iPhone meditation dreamcatcher lo-fi jean shorts. Church-key bitters vinyl narwhal lomo synth. Chambray literally flexitarian Marfa craft beer tilde. Synth small batch Portland 8-bit, American Apparel church-key disrupt skateboard brunch health
            goth listicle irony tofu artisan photo booth. Odd Future squid leggings paleo stumptown disrupt.</p>
          <p>Neutra Marfa McSweeney's asymmetrical Intelligentsia, wolf Brooklyn stumptown street art. Cardigan Intelligentsia viral, pickled crucifix forage wolf listicle normcore synth. Dreamcatcher keffiyeh cronut 90's, readymade sriracha fap mustache
            leggings Banksy Austin kale chips crucifix. Portland craft beer next level stumptown, heirloom four dollar toast tattooed McSweeney's hoodie shabby chic squid distillery before they sold out. Literally Tumblr ethical, cardigan 8-bit beard
            put a bird on it gastropub pour-over cornhole ugh lo-fi. Post-ironic shabby chic chillwave, semiotics salvia before they sold out flexitarian retro locavore distillery meditation letterpress cliche. Blue Bottle pork belly roof party Thundercats
            tattooed.
          </p>

        </div>
      </div>
    </div>
  </div>
</div>

关于html - 如何让 Bootstrap 固定导航栏不是全宽,顶部有横幅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29615867/

相关文章:

python - 将具有不同键的字典列表转换为值字符串列表

java - 在 JSP 中按 "Delete"键从服务器端删除 ArrayList 条目

javascript - 定位和样式 ajax 加载器

jquery - 工具提示和下拉切换不能一起使用

HTML、CSS - 页面顶部有一个我想删除的空白区域

javascript - 使用 JavaScript/jquery 将动态 html 模板打印到页面上

css - Laravel css 出现在标题标签上

html - 如何让banner图片全长延伸,logo居中?

javascript - Typeahead.js 干扰 Bootstrap 输入组

laravel - 具有可折叠组件的响应式布局