为什么不透明度不动画?

时间:2019-06-07 07:24:57

标签: css opacity

在以下代码中,“示例A”没有动画,而“示例B”却是动画。

唯一的区别是A过去不显示,B过去是隐藏的。

document.getElementById('set').onclick = function() {
  document.getElementById('a').classList.add('clicked');
  document.getElementById('b').classList.add('clicked');
};

document.getElementById('reset').onclick = function() {
  document.getElementById('a').classList.remove('clicked');
  document.getElementById('b').classList.remove('clicked');
};
.example {
  background: blue;
  transition: opacity 2000ms ease;
}

.example.clicked {
  opacity: 0;
}

.example:not(.clicked) {
  opacity: 1;
}

#a:not(.clicked) {
  display: none;
}

#b:not(.clicked) {
  visibility: hidden;
}
<button id="set">Show and fade out</button>
<button id="reset">Reset</button>

<div id="a" class="example">Example A</div>
<div id="b" class="example">Example B</div>

为什么两种不同的行为?为什么不透明度总是不活跃?

2 个答案:

答案 0 :(得分:0)

使用XComponentheight: 0代替height: auto

查看此答案:Transitions on the display: property

编辑:display: nonedisplay: none立即生效,因此我认为过渡无法正常进行。使用setTimeout,它仍然可以工作。

display: block
document.getElementById('set').onclick = function() {
  document.getElementById('a').style.display = "block";
  document.getElementById('a').style.opacity = 0;

  setTimeout(()=>{
    document.getElementById('a').style.opacity = 1;
  }, 0);
};

document.getElementById('reset').onclick = function() {
  document.getElementById('a').style.opacity = 0;
  setTimeout(()=>{
    document.getElementById('a').style.display = "none";
  }, 2000);
};
.example {
  background: blue;
  transition: opacity 2000ms ease;
  overflow: hidden;
  display: none;
}

.example.clicked {
  opacity: 1;
}

.example:not(.clicked) {
  opacity: 0;
}

#b:not(.clicked) {
  height: 0;
}

答案 1 :(得分:-1)

您应该将display: none上的#a:not(.clicked)更改为visibility: hidden,然后它才能正常工作。

display: none表示该标签不会出现。 visibility: hidden表示为标签分配了空间。它已渲染,但不可见。

document.getElementById('set').onclick = function() {
  document.getElementById('a').classList.add('clicked');
  document.getElementById('b').classList.add('clicked');
};

document.getElementById('reset').onclick = function() {
  document.getElementById('a').classList.remove('clicked');
  document.getElementById('b').classList.remove('clicked');
};
.example {
  background: blue;
  transition: opacity 2000ms ease;
}

.example.clicked {
  opacity: 0;
}

.example:not(.clicked) {
  opacity: 1;
}

#b:not(.clicked), #a:not(.clicked) {
  visibility: hidden;
}
<button id="set">Show and fade out</button>
<button id="reset">Reset</button>

<div id="a" class="example">Example A</div>
<div id="b" class="example">Example B</div>

相关问题