首页 > 解决方案 > 动画元素在外观上平滑淡入,但在消失时立即隐藏

问题描述

我有一个元素opacity: 0

当某个选择器匹配时,我想opcacity平滑过渡到1.

当该选择器不再匹配时,我想opacity立即恢复为0.

我怎么做?

PS 没有 JS,当然。

.the {
  display: inline-block;
  border: 1px solid deepskyblue;
  background-color: lightblue;
  padding: 2px 5px;
  border-radius: 4px;
  
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  opacity: 0;
  pointer-events: none;
}

input:checked ~ .the {
  opacity: 1;
}
<label>
  <input type="checkbox">
  Show element
  
  <span class="the">
    I'm the element to animate!
  </span>
</label>

标签: htmlcsscss-animationscss-transitions

解决方案


您可以添加transition:checked规则:

.the {
  display: inline-block;
  border: 1px solid deepskyblue;
  background-color: lightblue;
  padding: 2px 5px;
  border-radius: 4px;
  
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  opacity: 0;
  pointer-events: none;
}

input:checked ~ .the {
  transition: opacity .5s;
  opacity: 1;
}
<label>
  <input type="checkbox">
  Show element
  
  <span class="the">
    I'm the element to animate!
  </span>
</label>


推荐阅读