检测 HTML table 单元格的 textContent(value) 的变化并对变化的数据应用动画

Detect change of textContent(value) of HTML table cell and apply animation on changed data

我刚刚使用 Javascript 编码 HTML Table。 table的单元格数据每2秒更新一次API(一些统计数字数据), 这是我的代码:

function dataRenew {
  for(var i = 0;i < fooArray.length; i++) {
    var id = fooArrayID[i];
    document.getElementById(id).textContent = fooArray[i].someStatisticNumber;
    // id is for each cell
  }
}
//....
setInterval(function () {
  dataRenew();
}, 2000);

这很有效。但我想根据单元格的数据变化添加动画或一些效果,就像:

当 API 将单元格数据更新为新数据时,单元格的背景颜色会淡出并再次淡入。

console.log('Look ma, no JavaScript!');
@-webkit-keyframes invalid {
  from { background-color: red; }
  to { background-color: inherit; }
}
@-moz-keyframes invalid {
  from { background-color: red; }
  to { background-color: inherit; }
}
@-o-keyframes invalid {
  from { background-color: red; }
  to { background-color: inherit; }
}
@keyframes invalid {
  from { background-color: red; }
  to { background-color: inherit; }
}
.invalid {
  -webkit-animation: invalid 1s infinite; /* Safari 4+ */
  -moz-animation:    invalid 1s infinite; /* Fx 5+ */
  -o-animation:      invalid 1s infinite; /* Opera 12+ */
  animation:         invalid 1s infinite; /* IE 10+ */
}
td {
  padding: 1em;
}
<table>
  <tr>
    <td>true</td>
    <td class="invalid">false</td>
    <td>true</td>
    <td>true</td>
  </tr>
</table>

这个例子不是更新数据但是动画就是我想要的,反正这只是一个效果例子,我只是想知道如何在单元格数据变化时应用效果。

首选 Vanilla JS,但 jQuery 也可以

您可能正在寻找 MutationObserver,它提供了监视对 DOM 树所做更改的能力。如果您想观察 innerHTML 更改,则必须设置 subtree: true

感谢 Jax-p

这只是我的代码

td {
  transition: all 0.5s;
}

var config = {
  childList: true,
};

$(".fooID").each(function () { // fooID is td's id value
  var target = this;
  var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
      // console.log(mutation.target);
      // console.log(mutation.removedNodes[0].data); // mutation.removedNodes[0].data = old value
      // console.log(mutation.target.textContent); // mutation.target.textContent = new value
      if (
        parseFloat(mutation.target.textContent) <
        parseFloat(mutation.removedNodes[0].data)
      )
        mutation.target.style.color = "blue";
      else mutation.target.style.color = "red";
      setTimeout(function () {
        mutation.target.style.color = "black";
      }, 300);
    });
  });