【问题标题】:Transition applying when element added , not removed元素添加时应用过渡,而不是删除
【发布时间】:2015-05-13 04:10:43
【问题描述】:

我正在研究一个小的过渡效果,其中 div 的背景颜色每 4 个更改一次,问题是,仅当 添加 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。

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    您需要将过渡应用到主元素,因为一旦您删除了.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;
                }
    

    【讨论】:

    • 谢谢!我试过了,效果很好,但我想知道why?谢谢你的解释!
    • 没问题!不过请记住,只要将转换设置得尽可能广泛,就会转换 every 属性,如果您只想转换背景颜色,请使用 transition: background-color 2s
    • 另外,如果你觉得这回答了你的问题,别忘了标记为答案:)
    猜你喜欢
    • 2013-05-14
    • 2019-08-19
    • 2015-08-14
    • 2017-03-28
    • 2016-01-16
    • 1970-01-01
    • 2021-07-15
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多