Why does this CSS transition event not fire when t

2019-09-06 15:27发布

问题:

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.