我有一个实时提要,每隔几秒就会带来一些东西。我想突出显示新输入的信息,以便监视提要的人可以看到发生了变化。
现在每个元素在调用动画时都会闪烁。如何才能使最后插入的元素突出显示?
必须使用纯 javascript 且无插件。
var doc = document.getElementById('results');
function next(i) {
setTimeout(function() {
doc.innerHTML = '<p>Hi ' + i + '<p>' + doc.innerHTML;
next(++i);
}, 1000);
}
next(1);
@keyframes highlight {
0% {
background: red
}
100% {
background: none;
}
}
p {
animation: highlight 1s;
}
<div id="results">
</div>
编辑
我可以使用 first-child,但如果我有批量更新,它不会选择所有的。
var doc = document.getElementById('results');
function next(i) {
setTimeout(function() {
doc.innerHTML = '<p>Hi1 ' + i + '<p>'+'<p>Hs2 ' + i + '<p>' + doc.innerHTML;
next(++i);
}, 1000);
}
next(1);
@keyframes highlight {
0% {
background: red
}
100% {
background: none;
}
}
p:first-child {
animation: highlight 1s;
}
<div id="results">
</div>
最佳答案
我不得不问,你是故意使用 innerHtml 的吗?这是非常低效的(引用 this post )。您最好创建 DOM 元素并将它们附加到您的容器中。这也将使您拥有更通用的解决方案。
它还允许您使用选择器(例如类)来突出显示,并且批量更新将继续有效。
我确实将其更改为只运行 10 次:
HTML
<div id="results">
</div>
CSS
@keyframes highlight {
0% {
background: red
}
100% {
background: none;
}
}
.child {
animation: highlight 1s;
}
JS
var doc = document.getElementById('results');
function next(i) {
if(i < 10) {
setTimeout(function() {
var div = document.createElement("div");
div.className = "child";
div.textContent = "Hi " + i;
doc.insertBefore(div, doc.firstChild);
next(++i);
}, 1000);
}
}
next(1);
关于javascript - 最后插入的元素闪烁颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38062076/