单击外部关闭Bootstrap offcanvas侧边栏

时间:2016-09-20 12:16:01

标签: javascript jquery html css twitter-bootstrap

我试图修改Boostrap Offcanvas模板。

工作示例是http://getbootstrap.com/examples/offcanvas/

它对我来说非常完美,我唯一想补充的是通过点击/点击它来关闭侧边栏菜单(现在它只能通过点击切换按钮来工作)。

感谢您的帮助。

HTML

<div class="container">
  <div class="row row-offcanvas row-offcanvas-right">
    <div class="col-xs-12 col-sm-9">
      <p class="pull-right visible-xs">
        <button type="button" class="btn btn-primary btn-xs" data-toggle="offcanvas">Toggle nav</button>
      </p>
      <div class="row">
        <div class="col-xs-6 col-lg-4">
          <h2>Heading</h2>
          <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
          <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
        </div>
        <!--/.col-xs-6.col-lg-4-->
        <div class="col-xs-6 col-lg-4">
          <h2>Heading</h2>
          <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
          <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
        </div>
        <!--/.col-xs-6.col-lg-4--> 
      </div>
      <!--/row--> 
    </div>
    <!--/.col-xs-12.col-sm-9-->

    <div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar">
      <div class="list-group"> <a href="#" class="list-group-item active">Link</a> <a href="#" class="list-group-item">Link</a> <a href="#" class="list-group-item">Link</a> </div>
    </div>
    <!--/.sidebar-offcanvas--> 
  </div>
  <!--/row-->

CSS

@media screen and (max-width: 767px) {
  .row-offcanvas {
  position: relative;
  -webkit-transition: all .25s ease-out;
  -o-transition: all .25s ease-out;
  transition: all .25s ease-out;
  }

  .row-offcanvas-right {
   right: 0;
  }


  .row-offcanvas-right
  .sidebar-offcanvas {
    right: -50%; /* 6 columns */
  }


  .row-offcanvas-right.active {
    right: 50%; /* 6 columns */
  }

  .sidebar-offcanvas {
    position: absolute;
    top: 0;
    width: 50%; /* 6 columns */
  }
}

的jQuery

$(document).ready(function () {
  $('[data-toggle="offcanvas"]').click(function () {
    $('.row-offcanvas').toggleClass('active')
  });
});

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

$(document).click(function(e) {
    var target = e.target;
    if (!$(target).is('#sidebar') && !$(target).parents().is('#sidebar')) {
         $('.row-offcanvas').removeClass('active')
    }
});