首页 > 解决方案 > 选中/取消选中时如何使用相同的关键帧?

问题描述

我写了这样一个代码来在检查时操作不透明度。这行得通。

#check1:checked+.box {
  animation: blink 1s;
}

@keyframes blink {
  0%,
  99% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<input type="checkbox" id="check1">
<div class="box">
  <div class="content">
    <p>content</p>
    <button type="button">
      <label for="check1">click me</label>
    </button>
  </div>
</div>

我也想在取消勾选的时候做同样的操作,所以我添加了动画属性。

但是,这不起作用,检查时的动画也不起作用。为什么会这样?

#check1 + .box {
  animation: blink 1s;
}

#check1:checked + .box {
  animation: blink 1s;
}


@keyframes blink {
  0%, 99% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<input type="checkbox" id="check1">
<div class="box">
  <div class="content">
    <p>content</p>
    <button type="button">
      <label for="check1">click me</label>
    </button>
  </div>
</div>

另外,我定义了一个与另一个名称完全相同处理的动画,并且它正常工作。为什么会这样?有没有智能的 CSS 解决方案?

#check1+.box {
  animation: blink1 1s;
}

#check1:checked+.box {
  animation: blink2 1s;
}

@keyframes blink1 {
  0%,
  99% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@keyframes blink2 {
  0%,
  99% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<input type="checkbox" id="check1">
<div class="box">
  <div class="content">
    <p>content</p>
    <button type="button">
      <label for="check1">click me</label>
    </button>
  </div>
</div>

标签: htmlcss

解决方案


经历它,我希望它对你有用

   #check1+.box {
      opacity:1;transition: 1s;
    }
    #check1:checked+.box {
      opacity:0;transition: 1s;
    }
    <input type="checkbox" id="check1">
    <div class="box">
      <div class="content">
        <p>content</p>
        <button type="button">
          <label for="check1">click me</label>
        </button>
      </div>
    </div>


推荐阅读