默认情况下如何使Bootastrap导航栏切换打开?

时间:2018-10-20 18:36:20

标签: html css twitter-bootstrap

我有一个Bootstrap导航栏,使用切换按钮来切换,就像原始代码一样-如何在页面加载时打开它或GET /reset/OA/50l-94673624f6b9fa5a060a/?我尝试将collapse.show设置为data-toggle="collapse",它默认显示,但是需要单击两次才能关闭。如何默认将其打开并按预期工作?

data-toggle="collapse.show"

2 个答案:

答案 0 :(得分:1)

如果您希望在折叠模式下默认打开导航栏,则必须向包含 collapse 类的项中添加 show 类:

<div class="collapse show navbar-collapse" id="navbarSupportedContent">
    /* content */
</div>

参考:https://getbootstrap.com/docs/4.0/components/collapse/#example

我举一个例子,以便您可以看到它的工作原理...

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

<nav class="navbar navbar-expand-lg navbar-light bg-secondary">
  <a class="navbar-brand" href="#">
    BRAND
  </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse show navbar-collapse" id="navbarNav">
     <ul class="navbar-nav">
       <li class="nav-item">
         <a class="nav-link" href="#">Link 1</a>
       </li>
       <li class="nav-item">
         <a class="nav-link" href="#">Link 2</a>
       </li>
       <li class="nav-item">
         <a class="nav-link" href="#">Link 3</a>
       </li>
     </ul>
  </div>
</nav>

答案 1 :(得分:0)

尝试一下:

$(document).ready(function() {
  $("#navbar").click();
});
<button id="navbar" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
</button>