缓慢地从预处理的行中删除背景色

removing background color from prepended rows slowly

本文关键字:删除 背景色 预处理 缓慢      更新时间:2023-09-26

我通过单击按钮将行添加到预先存在的表中。为了区分添加了哪些行,我为添加的行添加了背景色。但是,我想在一段时间后删除此背景色或将其淡出。

以下是我现在正在做的事情:

    $("#numlist").prepend("<tr class='newrow'><td>somenum</td></tr>");

如何淡出newrow类?

下面还有一个例子:http://jsfiddle.net/Nx2nC/

我建议使用CSS动画:

@-mozilla-keyframes newRowAdded {
    from {
        background-color: #ffa;
    }
    to {
        background-color: #fff;
    }
}
@-ms-keyframes newRowAdded {
    from {
        background-color: #ffa;
    }
    to {
        background-color: #fff;
    }
}
@-o-keyframes newRowAdded {
    from {
        background-color: #ffa;
    }
    to {
        background-color: #fff;
    }
}
@-webkit-keyframes newRowAdded {
    from {
        background-color: #ffa;
    }
    to {
        background-color: #fff;
    }
}
@keyframes newRowAdded {
    /* 'from' is that starting position/frame */
    from {
        background-color: #ffa;
    }
    /* 'to' is the final position/frame */
    to {
        background-color: #fff;
    }
}
.newrow {
                  /* first: the animation-name,
                     second: the animation duration (s for seconds): */
    -moz-animation: newRowAdded 2s;
    -ms-animation: newRowAdded 2s;
    -o-animation: newRowAdded 2s;
    -webkit-animation: newRowAdded 2s;
    animation: newRowAdded 2s;
}

JS Fiddle演示。

使用CSS动画不可避免的缺点是,旧的浏览器,特别是但不限于Internet Explorer,将无法实现此解决方案。为了处理那些不兼容的浏览器,如果你愿意并且能够实现jQuery UI以及jQuery本身:

$("#add").click(function (event) {
    event.preventDefault();
    $("#numlist tbody").prepend("<tr class='newrow'><td>somenum</td></tr>").find('.newrow:first').css('background-color', '#ffa').animate({
        'background-color' : '#fff'
    }, 2000);
});

JS Fiddle演示。

请注意,jQuery本身不能动画化元素的colorbackground-color属性,但是jQuery UI可以。尽管有一个替代的jQuery颜色插件也添加了这个功能,它可能比添加最小化的(并且只有来自的相关模块)jQuery UI更轻。

参考文献:

  • Mozilla开发者网络的CSS存储库中的"使用CSS动画"

您可以使用setTimeout()来删除类

    var $el = $("#numlist").prepend("<tr class='newrow'><td>somenum</td></tr>");
    setTimeout(function() { $('.newrow',$el).removeClass('newrow')}, 1000);

你可以使用css转换来实现衰减效果

.newrow {
   background-color: red;
   transition: background-color 1s linear;
}
tr {
  background-color: none;
  transition: background-color 1s linear;
}

http://jsfiddle.net/Nx2nC/13/

试试这个:

$("#add").click(function (e) {    
  e.preventDefault();
  var $tr = $("<tr/>",{"class":"newrow","html":"<td>somenum</td>"}).hide();
    $("#numlist").prepend($tr.show("slow"));
    setTimeout(function(){
        $tr.css("background-color","#fff")
    },1500);
});

工作小提琴在这里:http://jsfiddle.net/Nx2nC/9/