jQuery: how to fade between classes?

2020-02-12 05:11发布

I need to be able to fade between classes and seamlessly transition any and all styles being applied to the element and its children. How can this be done using jQuery? I know how to add/remove classes but that is not the same as a nice transition between two drastically different colors.

标签: jquery css class
4条回答
手持菜刀,她持情操
2楼-- · 2020-02-12 05:46

jQuery UI has a toggleClass function that has an argument for duration:

http://jqueryui.com/demos/toggleClass/

For example, I do this on one of my sites (fade in/out the light class and fade/in out the dark class):

$('body').toggleClass('light', 250).toggleClass('dark', 250);
查看更多
等我变得足够好
3楼-- · 2020-02-12 05:50

Is this what you're trying to accomplish? Here's the jsFiddle

HTML:

<input type="button" id="toggle" value="toggle" />
<br />
<div id="classContainer">

    <div id = "class1">

    </div>
    <div id = "class2">
    </div>
</div>

jQuery:

$("#toggle").click(function (){
    if ($("#class1").is(":visible")) {
        $("#class1").fadeOut();
        $("#class2").fadeIn();
    }
    else {
        $("#class1").fadeIn();
        $("#class2").fadeOut();
    }
 });

CSS:

#classContainer
{
    position: relative;
}

#class1, #class2
{
    height: 100px;
    width: 100px;
    position: absolute;
    top: 0;
    left: 0;
}

#class1
{
    background-color: red;
    display: none;
}

#class2
{
    background-color: blue;
}
查看更多
手持菜刀,她持情操
4楼-- · 2020-02-12 06:08

Check out the color plugin for jQuery: https://github.com/jquery/jquery-color

查看更多
Anthone
5楼-- · 2020-02-12 06:08

Try fadeIn.

$(".myClass").fadeIn("slow");

http://api.jquery.com/fadeIn/

Although depending on the complexity you may need jQuery UI as other have mentioned.

查看更多
登录 后发表回答