为什么在添加两个类时不触发此CSS过渡事件? [英] Why does this CSS transition event not fire when two classes are added?

查看:78
本文介绍了为什么在添加两个类时不触发此CSS过渡事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.horizo​​ntalTranslate {...}

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 ='horizo​​ntalTranslate'; 实际上正在删除样式,从而导致CSS转换实际发生。但是,当我设置 box.className ='secondClass horizo​​ntalTranslate'; 时,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆