改变Div's CSS在一定的时间

Change A Div's CSS For A Certain Time

本文关键字:时间 CSS Div 改变      更新时间:2023-09-26
$("#team").css("background-color","blue");

我想把id:team的背景色变成蓝色,但是我只想把这个颜色变成4秒。

我该怎么做?

我已经谷歌了,但我找不到任何关于改变css给定的时间框架。

另外,从/到之前的设置淡出/入将是一个很好的触摸。

如果你想让它在4秒内呈现蓝色,你可以这样做:

var element = $( "#team" );
var oldColor = element.css( "background-color" );
element.animate( { "background-color": "blue" } )
       .delay( 4000 )
       .animate( { "background-color": oldColor } );

.animate()需要jQuery UI,否则可以直接使用.css()

你必须使用计时器功能:

setTimeout(function() { 
     $('#team').css('background-color', 'whatever'); 
}, 4000);

第二个参数是以毫秒为单位的计数,表示在调用第一个参数(函数)之前您希望等待多长时间。

没有内置的功能说"回到以前的样子";您必须在自己的代码中记住旧的值。

如果你不想使用jQuery UI插件(可能是因为它的大小),那么你可以手动做动画。

请看下面在jsFiddle中工作的代码。

function animblue(selector, from, to, step) {
    var
        target = $('#target'),
        color = from,
        next;
    next = function () {
        var hex = (Math.floor(color) < 16 ? '0' : '') + Math.floor(color).toString(16);
        target.css('background-color', '#' + hex + hex + 'ff');
        color += step;
        if (!((color < from && color < to) || (color > from && color > to))) {
            setTimeout(next, 10);
        }
    };
    next();
}
$('#action').on('click', function () {
    animblue('#target', 255, 0, -255 / 16);
    window.setTimeout(function () {
        animblue('#target', 0, 255, 255 / 16);
    }, 4000);
});​