Why does this CSS transition event not fire when two classes are added?

三世轮回 提交于 2019-12-25 03:57:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!