如何将转换添加到JavaScript切换类

How to add transition to JavaScript toggle class

本文关键字:JavaScript 添加 转换      更新时间:2023-12-18

我在JavaScript中制作了一个切换类,其中有一个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>

最后我的JavaScript是:

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';

您不能在背景图像上设置过渡效果,但有一些方法可以模拟。看看这个代码:

jsFiddle

HTML

<div>
    <span>HELOO</span>
</div>

CSS

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;
}

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

打开它http://jsfiddle.net/qtpCS/

使用CCD_ 1技术。