gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:35:25 28 4
gpt4 key购买 nike

在下面的示例中,我正在使用 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 中找到的最多内容关于这个特定主题( anchor 下方第 2nd 段):

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 来说是一种矫枉过正和额外的负载,而这很容易避免。当本身没有转换开始事件时,在这种情况下几乎不可能触发转换结束事件。

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

关于javascript - 当初始状态和最终状态相同时,不会触发 transitionend,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41634322/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com