为什么在显示 parent 时 transition-delay 对 child 元素不起作用?

Why does transition-delay not work on a child element when parent is shown?

这可能最好用一个例子来说明。我有一个 parent 和一个 child。默认情况下 parent 是隐藏的,除非它有 in class。它的 child 应该在 3 秒延迟后将其 background-color 从绿色转换为白色,只有当 parent 收到 in class.

所以当显示parent时,child的背景色已经是白色了。没有 3 秒的橙色过渡到白色。有人可以解释这里发生了什么吗?

$('button.show').on('click', () => {
  $('.parent').addClass('in');
});

$('button.hide').on('click', () => {
  $('.parent').removeClass('in');
});
.parent, .child {
  display: flex;
  align-items: center;
  justify-content: center;
}

.parent {
  background-color: orange;
  width: 300px;
  height: 300px;
}

.child {
  background-color: green;
  padding: 20px;
  width: 150px;
  height: 150px;
  transition: background-color 1s linear;
}

.parent:not(.in) {
  display: none;
}

.parent.in .child {
  background-color: white;
  transition-delay: 3s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="parent">
  <div class="child">
    <span>Background should start green, then turn white, but transition isn't happening.</span>
  </div>
</div>

<br>
<button type="button" class="show">Show parent</button>
<button type="button" class="hide">Hide parent</button>

您看不到过渡的原因是子项从未显示为第一种背景色。开始时 display:none 从父级继承,然后同时切换到父级显示和新颜色。

您需要先显示父项(以及继承的子项),然后更改子项的颜色。

JS

 $('button').on('click', () => {
     $('.parent').addClass('in');
     //Without settimeout this will run same time as first added class
     setTimeout(() => $('.parent').addClass('color'), 0);
 });

那么你就是 css

.parent.in.color .child {
    background-color: white;
    transition-delay: 3s;
}

考虑到父项的 display:none 起始条件,我对设置发生的确切时间感到有点困惑。

此代码段采用了稍微不同的路径 - 使用 CSS 动画,我发现它更易于控制。动画在显示父级之前不会设置,因此在时间上没有混淆的余地。

$('button.show').on('click', () => {
  $('.parent').addClass('in');
});

$('button.hide').on('click', () => {
  $('.parent').removeClass('in');
});
.parent,
.child {
  display: flex;
  align-items: center;
  justify-content: center;
}

.parent {
  background-color: orange;
  width: 300px;
  height: 300px;
}

.child {
  background-color: green;
  padding: 20px;
  width: 150px;
  height: 150px;
  animation-name: none;
}

.parent:not(.in) {
  display: none;
}

.parent.in .child {
  animation-name: change;
  animation-duration: 1s;
  animation-iteration-count: 1;
  animation-delay: 3s;
  animation-fill-mode: forwards;
}

@keyframes change {
  0% {
    background-color: green;
  }
  100% {
    background-color: white;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="child">
    <span>Background should start green, then turn white, but transition isn't happening.</span>
  </div>
</div>

<br>
<button type="button" class="show">Show parent</button>
<button type="button" class="hide">Hide parent</button>