如何将bootstrap固定导航栏不是全宽,顶部有横幅

时间:2015-04-13 22:04:49

标签: html css twitter-bootstrap

所以我刚刚开始使用bootstrap,我需要帮助设置一个导航栏。

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

横幅和顶部导航栏不是全宽。横幅长960px,我使用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文件(除了引导程序):

/* 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;
}

1 个答案:

答案 0 :(得分:1)

滚动到正确位置时,可以将导航栏调整为position: fixed。但是,这会使它超出DOM中的位置,因此您需要调整宽度和位置,并通过向容器元素添加边距来计算丢失的空间。您可能想要考虑其他一些事情,例如像navbar-fixed-top那样取出像bootstrap一样的border-radius。实际上,添加该类而不是设置position:fixed可能更好,但我在我的示例中遇到了一些其他问题,所以需要稍微调整一下。

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

我将ids添加到导航栏的关键部分,但您也可以通过其他方式获取它们(例如,如果您只有一个导航栏,则可以使用.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>