Bootstrap 2:如何通过检测响应的导航栏折叠事件来切换元素?

时间:2014-03-18 23:21:53

标签: javascript jquery twitter-bootstrap

以下是来自Bootstrap 2 docs的可折叠响应式导航栏,其中添加了搜索表单:

<div class="navbar">
  <div class="navbar-inner">
    <div class="container">

      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </a>

      <!-- Be sure to leave the brand out there if you want it shown -->
      <a class="brand" href="#">Project name</a>

      <div class="input-append">
        <input class="span2" id="appendedInputButton" type="text">
        <button class="btn" type="button">
          <i class="icon-search"></i>
          <span id="go-text">Go!</span>
        </button>
      </div>

      <!-- Everything you want hidden at 940px or less, place within here -->
      <div class="nav-collapse collapse">
        <!-- .nav, .navbar-search, .navbar-form, etc -->
      </div>

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

当导航栏折叠时,我还想隐藏<span id="go-text">Go!</span>

我尝试过类似的事情:

$(".btn-navbar").on("show hide", function (event) {
    $("#go-text").toggle();
});

似乎没有用。任何人都知道如何让这个工作?

2 个答案:

答案 0 :(得分:0)

没有javascript只需要我所谓的&#34;媒体查询&#34; (随意在评论中纠正我):

// your-stylesheet.less
@media (max-width: @navbarCollapseWidth) {
  #go-text {
    display: none;
  }
}

答案 1 :(得分:0)

根据HTML标记,您可以在元素#go-text中插入元素<div class="nav-collapse collapse">

另一个选择是监听CSS媒体查询更改。您可以使用函数window.matchMedia

将事件侦听器添加到css媒体查询
if (window.matchMedia) { //only modern browsers

    function widthChange(mq) {
        var shouldShow = mq.matches; //bollean

        $("#go-text").toggle(shouldShow);
    }

    var mq = window.matchMedia("(min-width: 940px)") //the width that bootstrap in its media queries
    mq.addListener(widthChange);
}