上次插入的元素闪烁颜色

Last inserted element flash color

本文关键字:闪烁 颜色 元素 插入      更新时间:2023-09-26

我有一个实时提要,每隔几秒钟就会带来一些东西。我想突出显示新输入的信息,这样监控提要的人就可以看到一些变化。

现在,调用动画时,每个元素都会闪烁。如何使其仅高亮显示最后插入的元素?

必须使用纯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>

编辑

我可以使用第一个子项,但如果我有批量更新,它不会选择所有子项。

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的吗?它的效率非常低(参考这篇文章(。最好创建DOM元素并将它们附加到容器中。这也将允许您有一个更通用的解决方案。

它还允许您使用选择器(如类(作为高亮显示,并且批量更新将继续工作。

JSFiddle

我确实把它改成只运行了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);

使用第一个类型的伪选择器。

编辑:如果要批量插入和闪存,最简单的方法是用类包装div中的段落,并在div上使用first-of-type选择器,而不是在p上。

var doc = document.getElementById('results');
function next(i) {
  setTimeout(function() {
    doc.innerHTML = '<div class="inserted"><p>Hi1 ' + i + '<p>'+'<p>Hs2 ' + i + '<p></div>' + doc.innerHTML;
    next(++i);
  }, 1000);
}
next(1);
@keyframes highlight {
  0% {
    background: red
  }
  100% {
    background: none;
  }
}
.inserted:first-of-type {
  animation: highlight 1s;
}
<div id="results">
</div>

如果最后一个元素总是在#results中前置,则使用CSS伪选择器。

p:first-child {
    animation: highlight 1s;
}

Fiddle:https://jsfiddle.net/uz2weL3z/


如果您希望始终以上次插入为目标,则使用JavaScript如下:

setTimeout(function() {
    doc.innerHTML = '<p class="last">Hi ' + i + '<p>' + doc.innerHTML;
    setTimeout(function() {
        for(var j=0; j<els.length; j++) {
            els[j].className = "";
        }
    }, 1000);
    next(++i);
}, 1000);

超时1秒,因为您的动画为1秒

Fiddle:https://jsfiddle.net/uz2weL3z/1/