js中的颜色变化平滑

时间:2014-05-31 14:50:25

标签: javascript jquery css

我有这行代码,在某些事件改变颜色之后:

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

如何修改它以平滑地改变颜色,所以在原始颜色和#fff之间褪色需要1秒钟?

我知道这很容易,但我有一段时间没有这样做而忘了。 感谢

jsfiddle:HERE

4 个答案:

答案 0 :(得分:2)

没有任何额外插件的解决方案

1。添加此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; }

您可以将 1s 修改为您想要的任何时间值,如果您愿意,也可以使用 ms

2. 使用此jQuery代码:

$(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.

答案 1 :(得分:1)

您可以使用CSS转换:

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

答案 2 :(得分:0)

jQuery UI附带一个颜色插件,可以让你为颜色设置动画。

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

答案 3 :(得分:0)

如果您想从js中进行操作:

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

或者您可以将其添加到CSS中:

#mydiv {
     transition: all 2s;
}
相关问题