“ toggleClass()”无法正常工作

时间:2018-07-02 11:15:22

标签: javascript jquery html css

.toggleClass()方法仅将“类”添加到我的选择中,因此,当我单击时,得到的全部是:

<div id="toggle" class>
...

代替

<div id="toggle" class="on">
...

我一直试图弄清楚它大约2个小时,阅读有关同一问题的帖子,但是即使结果是这样,也似乎与我的情况不同。

JavaScript的第一步只是给加载屏幕添加动画,然后将其隐藏

$(function() {
  $(".loader_gif_wrapper").fadeOut(1000, function() {
    $(".slider").animate({
      width: ["0%", "swing"]
    }, 2000, function() {
      // Animation complete.
      $(".loader_page_wrapper").hide();
      // FIN ANIMACIONES LOADING


      $("#toggle").click(function() {
        $(this).toggleClass('on');
        //$("nav").toggle();
      });
    });
  });
});
#toggle {
  position: absolute;
  left: 3rem;
  top: 3rem;
  z-index: 10000;
  width: 40px;
  height: 40px;
  cursor: pointer;
  float: right;
  transition: all 0.3s ease-out;
  opacity: 1;
  visibility: visible;
}

#toggle .span {
  height: 3px;
  background: #ffffff;
  transition: all 0.3s ease-out;
  backface-visibility: hidden;
  margin: 5px auto;
  border: solid 1px $tres;
} //#toggle.on{
//    border: solid 0px $tres;}
#toggle.on #one {
  transform: rotate(45deg) translateX(2px) translateY(4px);
}

#toggle.on #two {
  opacity: 0;
}

#toggle.on #three {
  transform: rotate(-45deg) translateX(8px) translateY(-10px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="toggle">
  <div class="span" id="one">One</div>
  <div class="span" id="two">Two</div>
  <div class="span" id="three">Three</div>
</div>

1 个答案:

答案 0 :(得分:1)

您必须将事件声明放在回调之外,以便确保无论是否达到回调,在所有情况下都将附加事件:

$(function() {
  $(".loader_gif_wrapper").fadeOut(1000, function() {
    $(".slider").animate({
      width: ["0%", "swing"]
    }, 2000, function() {
      // Animation complete.
      $(".loader_page_wrapper").hide();
    });
  });

  $("#toggle").click(function() {
    $(this).toggleClass('on');
    //$("nav").toggle();
  });
});

工作示例

$(function() {
  $("#toggle").click(function() {
    $(this).toggleClass('on');
  });
});
#toggle {
  position: absolute;
  left: 3rem;
  top: 2rem;
  z-index: 10000;
  width: 40px;
  height: 30px;
  cursor: pointer;
  float: right;
  transition: all 0.3s ease-out;
  opacity: 1;
  visibility: visible;
  background-color: green;
}

#toggle .span {
  height: 3px;
  background: #ffffff;
  transition: all 0.3s ease-out;
  backface-visibility: hidden;
  margin: 5px auto;
  border: solid 1px;
  border: solid 0px;
}

#toggle.on #one {
  transform: rotate(45deg) translateX(2px) translateY(4px);
}

#toggle.on #two {
  opacity: 0;
}

#toggle.on #three {
  transform: rotate(-45deg) translateX(8px) translateY(-10px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="toggle">
  <div class="span" id="one"></div>
  <div class="span" id="two"></div>
  <div class="span" id="three"></div>
</div>