Jquery Burger Menu不会正确应用课程

时间:2018-04-05 11:19:24

标签: jquery html css

如果我点击burger元素,该函数会运行,但不会应用所需的类。

当我读到它时,可能有任何一些亮点,这看起来应该可以工作,但我没有看到在dom中应用的类,理论上应用下拉菜单应该是可见的。< / p>

HTML(最小化示例):

<header>
  <div class = "navwrap">
  <h1 class = "logo">Logo </h1>
  <nav>
    <a class = "burger-nav"> </a>
    <h2> Main Nav</h2>
    <ul>
      <li><a href="">Home</a></li>
      <li><a href="">Home</a></li>
      <li><a href="">Home</a></li>
    </ul>
  </nav>
  </div>
</header>

<script src="js/jQuery.js"></script>
<script src="js/vendor/modernizr-3.5.0.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/nav.js"></script>
<script src="js/main.js"></script>

CSS:

@media screen and (max-width: 480px) {

  .burger-nav {
    display: block;
    height: 40px;
    width:100%;
    background: url(../img/navicon.png) no-repeat 98% center;
    background-color: blue;
    cursor:pointer;
  }

  header .navwrap{
    padding:0;
    width:100%;
  }

  header nav ul {
    overflow:hidden;
    background: #505050;
    height: 0;
  }

  header nav ul .open {
    height: auto;
  }

  header nav ul li {
    float: none;
    text-align: left;
    width: 100%;
    margin: 0;
  }

  header nav ul li a {
  color: #fff;
  padding: 10px;
  border-bottom: 1px solid #404040;
  display: block;
  margin:0;
  }

}

Jquery的:

$(document).ready(function() {

$(".burger-nav").on("click", function() {

  alert("Clicked");

    $("header nav ul").toggleClass("open");

});

});

1 个答案:

答案 0 :(得分:1)

问题在于css规则,

而不是 header nav ul .open 将其设置为 header nav ul.open (删除ul.space类之间的空格),对元素的第一次搜索是insdu有.open类的ul,第二个有.open类的ul,这就是区别

见下面的代码段

$(document).ready(function() {

  $(".burger-nav").on("click", function() {

      $("header nav ul").toggleClass("open");

  });

});
@media screen and (max-width: 680px) {

  .burger-nav {
    display: block;
    height: 30px;
    width:40px;
    background: url(https://cdn.css-tricks.com/wp-content/uploads/2012/10/threelines.png) no-repeat 98% center;
    background-color: blue;
    background-size: 50px;
    cursor:pointer;
  }

  header .navwrap{
    padding:0;
    width:100%;
  }

  header nav ul {
    overflow:hidden;
    background: #505050;
    height: 0 ;
  }

  header nav ul.open {
    height: auto;
  }

  header nav ul li {
    float: none;
    text-align: left;
    width: 100%;
    margin: 0;
  }

  header nav ul li a {
  color: #fff;
  padding: 10px;
  border-bottom: 1px solid #404040;
  display: block;
  margin:0;
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>

<header>
  <div class = "navwrap">
  <h3 class = "logo">Logo </h3>
  <nav>
    <a class = "burger-nav"> </a>
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">Home</a></li>
      <li><a href="#">Home</a></li>
    </ul>
  </nav>
  </div>
</header>