简体   繁体   中英

Smooth color change in js

I have this line of code, which after some event changes color:

$('li', this).css('color', '#fff');

How to modify it to change colour smoothly, so it takes eg 1 second to fade between the original color and #fff ?

I know it's very easy, but i haven't done it for a while and forgot. thanks

jsfiddle: HERE

Solution without any additional plugins

1. Add this CSS:

nav li {
   -webkit-transition:color 1s ease;
   -moz-transition:color 1s ease;
   -o-transition:color 1s ease;
   transition:color 1s ease;
}

.white_color { color:#fff; }

You can modify 1s to whatever time value you want, you can also use ms if you like.

2. Use this jQuery code:

$(document).ready(function () {
    $("nav a").mouseenter(function () {
        if ($(this).data('fading')) //EXIT IF WE ARE FADING
        return;
        $('div', this).stop(true, false).animate({
            'height': '45px'
        }, 100);
        $('li', this).addClass('white_color'); // THIS IS THE LINE I'M AFTER - I want the color to change smoothly, not instantly
        $('li', this).stop(true, false).animate({
            'padding-top': '15px'
        }, 200);
    }).mouseleave(function () {
        if ($(this).data('fading')) return;
        $('li', this).removeClass('white_color');
        $('div', this).stop(true, false).animate({
            'height': '0px'
        }, 300);

        $('li', this).stop(true, false).animate({
            'padding-top': '65px'
        }, 500);
    });

});

jsFiddle demo.

You could use CSS transition:

li
{
 color: #000;
 transition: color 1s ease;
}

jQuery UI comes with a color plugin which allows you to animate colors.

$('li', this).animate({
    color: "#fff"
}, 1000);

If you want to do it from your js:

document.getElementById("myDIV").style.transition = "all 2s";

Or you can just add it to your CSS:

#mydiv {
     transition: all 2s;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM