这是我的表格行,我的要求是第一次以黄色显示行,4 秒后颜色变淡。这怎么可能。
$('#invoice').prepend('<tr><td>Invoice</td><td>analysing</td><td>analysing</td></tr>');
最佳答案
我为您提供了三种解决方案:纯 Javascript、jQuery 和 CSS
Pure Javascript Solution:
这是创建一个新的 tr
并将其附加到表中,并将 innerHTML 设置为 td
标记。几乎与附加到表中的 jQuery 相同,但有一点不同。我已经这样做了,所以我可以针对刚刚为 setTimeout
创建的特定 tr
运行。
function demo(){
var table = document.getElementById('invoice');
var tr = document.createElement('tr');
table.appendChild(tr);
tr.innerHTML='<td>Invoice</td><td>analysing</td><td>analysing</td>';
// Opacity change
setTimeout(function(){ tr.style.opacity="0.5"}, 4000);
//Background only
//setTimeout(function(){ tr.style.background="rgba(255,255,0,.2)"}, 4000);
}
table tr{background:yellow;opacity:1;}
<button id="create" onclick="demo()">Add</button>
<table id="invoice">
<tr><td>Invoice</td><td>analysing</td><td>analysing</td></tr>
</table>
更新,我已经注释掉背景变化并将其替换为不透明度,因为它也会淡化内容。如果您只想更改背景,请移除不透明线并取消注释背景线。
jQuery Solution:
$(document).ready(function () {
$( "#create" ).click(function() {
$('#invoice').prepend('<tr><td>Invoice</td><td>analysing</td><td>analysing</td></tr>');
setTimeout(function () {
$('tr').css('transition', 'opacity .5s ease-in');
$('tr').css('opacity', '0.5');
}, 4000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="create">Add</button>
<table id="invoice">
</table>
上述 jQuery 解决方案的一个问题:如果您创建多个 td
,计时器将从创建的第一个开始计时,因此您可能会发现元素在不到 4 秒内发生变化
CSS Solution:
我知道这个问题中没有标记 CSS,但我相信解决方案越多越好。
我已经添加了对浏览器的支持,所以你应该不会有任何问题,你可以测试它们并删除你不想要的。
// Jquery for Demo purposes of creating dynamic elements.
$(document).ready(function () {
$( "#create" ).click(function() {
$('#invoice').prepend('<tr><td>Invoice</td><td>analysing</td><td>analysing</td></tr>');
});
});
#invoice tr {
background:yellow;
-webkit-animation: OpFade 1s; /* Safari, Chrome and Opera > 12.1 */
-moz-animation: OpFade 1s; /* Firefox < 16 */
-ms-animation: OpFade 1s; /* Internet Explorer */
-o-animation: OpFade 1s; /* Opera < 12.1 */
animation: OpFade 1s;
animation-delay: 4s;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
}
@keyframes OpFade {
from { opacity: 1;}
to { opacity: 0.5;}
}
/* Firefox < 16 */
@-moz-keyframes OpFade {
from { opacity: 1; }
to { opacity: 0.5; }
}
/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes OpFade {
from { opacity: 1; }
to { opacity: 0.5; }
}
/* Internet Explorer */
@-ms-keyframes OpFade {
from { opacity: 1; }
to { opacity: 0.5; }
}
/* Opera < 12.1 */
@-o-keyframes OpFade {
from { opacity: 1; }
to { opacity: 0.5; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="create">Add</button>
<table id="invoice">
<tr><td>Invoice</td><td>analysing</td><td>analysing</td></tr>
</table>
如果您对上述任何源代码有任何疑问,请随时在下方发表评论,我会尽快回复您。
我希望这对您有所帮助,编码愉快!
关于javascript - 表格行在一段时间不工作后变得淡出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38072482/