当初始状态和最终状态相同时,不会触发 transitionend

transitionend is not fired when initial state and final state are the same

在下面的示例中,我正在使用 CSS 进行 background-color 转换并尝试处理两个 div 的 transitionend 事件。

不幸的是,transitionend 不会为 div2 触发,因为初始和最终背景颜色相同:

var div1 = $('#div1');
var div2 = $('#div2');

$('#toggle').on('click', function() {
   div1.toggleClass('toggled');
   div2.toggleClass('toggled');
})

div1.on('transitionend', function() {
   console.log('div1 transitionend')
})

div2.on('transitionend', function() {
   console.log('div2 transitionend')
})
div {
  width: 100px;
  height: 100px;
  transition: background-color .5s;
}

#div1 {
  background-color: red;
}

#div2 {
  background-color: green;
}

.toggled {
  background-color: green !important;
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

<div id="div1"></div>

<div id="div2"></div>

<button id="toggle">Toggle animation</button>

即使在初始状态和最终状态相同的情况下,如何实现处理 transitionend

转换通常发生在 style-change-event 发生时。也就是说,当元素的样式(属性 或更多的值)发生变化时,将开始转换。 W3C 规范(正如预期的那样)没有定义何时触发样式更改事件并将其留给实现。

以下是我在 W3C Specs 中可以找到的关于这个特定主题的最多内容(2nd para below anchor):

When a style change event occurs, implementations must start transitions based on the computed values that changed in that event.

实际上,以下似乎是过渡何时开始的更具决定性的定义。这是在 this anchor:

指向的部分末尾找到的

If all of the following are true:

  • the element does not have a running transition for the property,
  • the before-change style is different from and can be interpolated with the after-change style for that property,
  • the element does not have a completed transition for the property or the end value of the completed transition is different from the after-change style for the property,
  • there is a matching transition-property value, and
  • the combined duration is greater than 0s,

then implementations must remove the completed transition (if present) from the set of completed transitions and start a transition whose:

  • start time is the time of the style change event plus the matching transition delay,
  • end time is the start time plus the matching transition duration,
  • start value is the value of the transitioning property in the before-change style,
  • end value is the value of the transitioning property in the after-change style,
  • reversing-adjusted start value is the same as the start value, and reversing shortening factor is 1.

现在,根据我对 UA 如何工作以及它们将如何优化的理解,当元素上设置的 none 属性设置为正在发生变化。这对 UA 来说是一种矫枉过正和额外的负载,而这很容易避免。当本身没有转换开始事件时,在这种情况下几乎不可能触发转换结束事件。

因此,看起来您很可能必须使用一些虚拟的 属性 更改(或)使用其值等于 transition-duration + transition-delay 的计时器来模仿 transitionend.