未应用ToggleClass规则

时间:2018-08-24 12:14:00

标签: javascript html css

我有以下HTML / CSS / JS代码:

function addClass() {
  document.getElementById('shopping-cart-body').classList.add('open');
}

function removeClass() {
  document.getElementById('shopping-cart-body').classList.remove('open');
}
.cart-preview .body {
  visibility: hidden;
  position: fixed;
  height: 100%;
  top: 0;
  width: 400px;
  background-color: #fff;
  right: -400px;
}

.cart-preview .body .open {
  visibility: visible;
  transition: right 1s linear;
  right: 0px;
}
<div id="blockcart-wrapper">
  <div class="blockcart cart-preview">
    <div class="header">
      <a rel="nofollow" href="#">
        <img class="cart-icon" src="https://placehold.it/100" onclick="addClass()">
      </a>
    </div>
    <div class="body" id="shopping-cart-body">
      <div class="close"><a href="" onclick="removeClass()">X</a></div>
      <ul>
      </ul>
      <div class="cart-subtotals">
        <div class="products">
          <span class="label">Subtotal</span>
          <span class="value">0</span>
        </div>
        <div class="">
          <span class="label"></span>
          <span class="value"></span>
        </div>

        <div class="shipping">
          <span class="label">Shipping</span>
          <span class="value">0</span>
        </div>
        <div class="">
          <span class="label"></span>
          <span class="value"></span>
        </div>
      </div>
      <div class="cart-total">
        <span class="label">Total</span>
        <span class="value">0</span>
      </div>
      <div class="checkout">
        <button><a href="#">Checkout</a></button>
      </div>
    </div>
  </div>
</div>

我也尝试使用切换,当我提醒元素的类列表时,会显示新的类,但是未应用css规则,则该元素变得不可见。有趣的是:在提醒班级时,缺少主体的超类(购物车预览),但是有一个新的类(开放)。

出于可读性考虑,css仅包含两个所需的类,而不包含HTML部分的整个样式。

有人可以解释一下,为什么这不起作用?

1 个答案:

答案 0 :(得分:4)

您的css在具有 .body 类的元素下寻找具有css类 .open 的元素。该元素不存在。如果要让CSS应用于两个类的元素,请使用 .body.open

.cart-preview .body {
  visibility: hidden;
  position: fixed;
  height: 100%;
  top: 0;
  width: 400px;
  background-color: #fff;
  right: -400px;
}

.cart-preview .body.open {
  visibility: visible;
  transition: right 1s linear;
  right: 0px;
}
相关问题