如何向JavaScript切换类添加转换

如何向JavaScript切换类添加转换,javascript,html,css,toggle,transition,Javascript,Html,Css,Toggle,Transition,我用JavaScript制作了一个toggle类,其中有一个div,可以在鼠标悬停时切换它的类。div的一个类具有彩色背景,另一个类具有图像。问题是图像在瞬间出现,并且传输不平稳 我的css代码是: .container{ } .first{ height: 100%; width: 33%; position: absolute; background-color: #ecf0f1; top: 0px; left: 0px; backg

我用JavaScript制作了一个toggle类,其中有一个div,可以在鼠标悬停时切换它的类。div的一个类具有彩色背景,另一个类具有图像。问题是图像在瞬间出现,并且传输不平稳

我的css代码是:

.container{
}

.first{
    height: 100%;
    width: 33%;
    position: absolute;
    background-color: #ecf0f1;
    top: 0px;
    left: 0px;
    background-color: none;
    -webkit-transition: all 0.5s ease-in-out;
}
.sec{
    height: 100%;
    width: 33%;
    position: absolute;
    background-color: #ecf0f1;
    top: 0px;
    left: 0px;
    z-index: 5;
    background: url(1.jpg);
    background-color: none;
    -webkit-transition: all 0.5s ease-in-out;
} 
我的HTML代码是:

<div id="container" class="first"><span>HELOO</span>
</div>

您不能在背景图像上设置过渡效果,但可以通过某种方式进行模拟。请看以下代码:

HTML


只是为了学习,如果您坚持使用javascript切换类

检查一下


使用
:在
技术之后。

为什么不使用纯css来实现它呢。我认为它更简单。我不认为有任何纯css的方式来添加图像之间的转换,如果有,那么我会喜欢它,因为我在css方面比我的JavaScript更强大。你应该阅读Mohsen的答案。你使用的浏览器是什么-webkit转换只在Chrome上运行。这不是主要问题。javascript有很多工作要做。显然,纯css更好。
this.classList.toggle('first');
        this.classList.toggle('sec');
        document.getElementById('#container').style.WebkitTransition = 'all 0.5s';
    }
    document.querySelector('#container').addEventListener('mouseenter', a )
    document.querySelector('#container').addEventListener('mouseout', a )
    document.getElementById('#container').style.WebkitTransition = 'all 0.5s';
<div>
    <span>HELOO</span>
</div>
div{
    width:200px;
    height:200px;
    background:url(http://lorempixel.com/200/200);
    position:relative;
}
span{
    position:absolute;
    width:100%;
    height:100%;
    background-color:#ddd;
    -webkit-transition:all 0.5s ease;
    -moz-transition:all 0.5s ease;
    -ms-transition:all 0.5s ease;
    -o-transition:all 0.5s ease;
    transition:all 0.5s ease;
}
span:hover{
    background-color:transparent;
}