为什么在添加两个类时不触发此CSS过渡事件? [英] Why does this CSS transition event not fire when two classes are added?
问题描述
CSS
.horizontalTranslate {
-webkit-transition: 3s;
}
.secondClass {
background: red;
}
HTML
<div class='box'></div>
JS
var box = document.querySelector('.box');
box.addEventListener('webkitTransitionEnd', function(evt) {
alert('Finished transition!');
}, false);
function transitionBox() {
// this works
box.className = 'horizontalTranslate';
// this does not work
// box.className = 'secondClass horizontalTranslate';
}
setTimeout(transitionBox, 100);
为什么在添加两个类而不是一个类时不触发转换事件?我还尝试了链接我的CSS选择器,例如 .secondClass.horizontalTranslate {...}
。
Why does the transition event not fire when two classes are added rather than one? I've also tried chaining my CSS selector, a la .secondClass.horizontalTranslate { ... }
.
推荐答案
原因是 box.className ='horizontalTranslate';
实际上正在删除样式,从而导致CSS转换实际发生。但是,当我设置 box.className ='secondClass horizontalTranslate';
时,DOM节点的样式不会更改,并且不会触发任何事件。
The reason is that box.className = 'horizontalTranslate';
is actually removing styling, causing the CSS transition to actually happen. But when I set box.className = 'secondClass horizontalTranslate';
, the styling of the DOM node is not changing and no event is fired.
另一种写 transitionBox
的方法是:
function transitionBox() {
box.classList.add('horizontalTranslate');
box.classList.add('blue');
}
如果 blue
发生更改 box
的样式,也可以。
If blue
changes the styling of box
, this works too.
这篇关于为什么在添加两个类时不触发此CSS过渡事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!