问题
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);
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 { ... }
.
回答1:
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.
Another way to write transitionBox
is this:
function transitionBox() {
box.classList.add('horizontalTranslate');
box.classList.add('blue');
}
If blue
changes the styling of box
, this works too.
来源:https://stackoverflow.com/questions/24513581/why-does-this-css-transition-event-not-fire-when-two-classes-are-added