添加元素时应用的过渡,而不是删除

时间:2015-05-12 20:01:39

标签: javascript jquery css3

我正在研究一个小的过渡效果,其中div的背景颜色每4个更改一次,问题是,仅当添加 bg时,bg颜色会随着过渡而变化颜色而非删除 bg颜色:

HTML ::

<div class="test-it" id="test-it">
    HELLO
</div> 

CSS ::

.test-it {
    height: 200px;
    width: 200px;
    background: #eee;
    line-height: 200px;
    text-align: center;
    font-family: verdana;
    text-transform: uppercase;
    color: #fff;
    font-size: 40px;
    font-weight: bold;
}

.red {
    background: red;
    -webkit-transition: 2s;
    -o-transition: 2s;
    transition: 2s;
}

和JS代码::

(function() {

    var apollo = {};

    apollo.hasClass = function(elem, className) {
        return elem.classList.contains(className);
    };

    apollo.addClass = function(elem, className) {
        elem.classList.add(className);
    };

    apollo.removeClass = function(elem, className) {
        elem.classList.remove(className);
    };

    apollo.toggleClass = function(elem, className) {
        elem.classList.toggle(className);
    };

    window.apollo = apollo;

})();

apollo.addClass(document.body, 'test');

apollo.addClass(document.getElementById('test-it'), 'red');

var $str = apollo.hasClass(document.getElementById('test-it'), 'red');


var run = function() {

    setTimeout(function() {
        apollo.toggleClass(document.getElementById('test-it'), 'red');
        setTimeout(function() {
            run();
        }, 2000);

    }, 2000);

}

run();

console.log($str);

不要过多地研究JS代码,因为错误或所需的行为需要在CSS中,所以有人可以解释为什么当类.red是时,不会应用转换。脱掉?

<。>类.red具有以下CSS ::

.red {
    background: red;
    -webkit-transition: 2s;
    -o-transition: 2s;
    transition: 2s;
}

那么,当班级被取消时,为什么2秒过渡不适用?

谢谢。

亚历-Z。

1 个答案:

答案 0 :(得分:2)

您需要将转换应用于main元素,因为一旦删除.red类,转换就不再是元素的一部分,因此没有转换。

所以你的CSS应该是这样的

.test-it {
                height: 200px;
                width: 200px;
                background: #eee;
                line-height: 200px;
                text-align: center;
                font-family: verdana;
                text-transform: uppercase;
                color: #fff;
                font-size: 40px;
                font-weight: bold;
                -webkit-transition: 2s;
                -o-transition: 2s;
                transition: 2s;
            }
            .red {
                background: red;
            }
相关问题