[英]Detect change of textContent(value) of HTML table cell and apply animation on changed data
我剛剛使用 Javascript 對 HTML 表進行了編碼。表格的單元格數據通過 API(一些統計數字數據)每 2 秒更新一次,這是我的代碼:
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 更新為新數據時,單元格的背景顏色 go 淡出並再次淡入。
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>
這個例子不是更新數據,但animation正是我想要的,反正這只是一個效果例子,我只是想知道當單元格數據發生變化時如何應用效果。
首選 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); }); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.