You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为HTML表格单元格数据变更添加动画效果?

实现表格单元格数据更新时的背景过渡动画

你已经有了定时更新数据的基础代码,要加上动画其实很简单——关键是只在数据真正变化时触发一次动画,而不是一直循环播放。下面我给你两种实现方案,优先原生Vanilla JS,也附上jQuery版本。

第一步:调整CSS动画(去掉无限循环)

首先把你原来的CSS动画改成只播放一次,并且确保动画结束后单元格回到默认样式:

/* 兼容各主流浏览器的动画定义 */
@-webkit-keyframes updateFlash {
  from { background-color: red; }
  to { background-color: inherit; }
}
@-moz-keyframes updateFlash {
  from { background-color: red; }
  to { background-color: inherit; }
}
@-o-keyframes updateFlash {
  from { background-color: red; }
  to { background-color: inherit; }
}
@keyframes updateFlash {
  from { background-color: red; }
  to { background-color: inherit; }
}

/* 动画类:只播放一次,结束后保持最终状态 */
.update-flash {
  -webkit-animation: updateFlash 1s forwards;
  -moz-animation: updateFlash 1s forwards;
  -o-animation: updateFlash 1s forwards;
  animation: updateFlash 1s forwards;
}

td { 
  padding: 1em;
  transition: background-color 0.3s; /* 可选:让背景过渡更丝滑 */
}

这里把动画命名为updateFlash,用forwards代替infinite,确保动画结束后停在最后一帧(继承父元素背景),不会重复播放。

第二步:原生JS实现(优先方案)

修改你的dataRenew函数,只有当新数据和当前单元格内容不同时才触发动画,同时处理动画结束后的类移除:

function dataRenew() { 
  for(var i = 0; i < fooArray.length; i++) { 
    var id = fooArrayID[i];
    var cell = document.getElementById(id);
    var newValue = fooArray[i].someStatisticNumber.toString(); // 转字符串避免类型判断误差
    
    // 仅数据变化时执行更新和动画
    if (cell.textContent !== newValue) {
      // 先移除类(防止重复添加导致动画不触发)
      cell.classList.remove('update-flash');
      // 强制浏览器重绘(否则DOM更新不及时,动画可能不生效)
      void cell.offsetWidth;
      // 更新数据并添加动画类
      cell.textContent = newValue;
      cell.classList.add('update-flash');
      
      // 动画结束后自动移除类,方便下次触发
      cell.addEventListener('animationend', function removeClass() {
        this.classList.remove('update-flash');
        this.removeEventListener('animationend', removeClass); // 清理监听避免内存泄漏
      });
    }
  } 
}

// 保持原有的定时更新逻辑
setInterval(function () { 
  dataRenew(); 
}, 2000);

核心细节:

  • 先判断新旧值是否不同,避免无意义的动画触发
  • 用void cell.offsetWidth强制浏览器重绘,解决DOM更新不及时导致的动画失效问题
  • 监听animationend事件,动画结束后自动移除类,确保下次更新能正常触发动画

可选:jQuery简化版

如果项目里已经引入jQuery,代码会更简洁:

function dataRenew() { 
  $.each(fooArray, function(i) { 
    var id = fooArrayID[i];
    var $cell = $('#' + id);
    var newValue = fooArray[i].someStatisticNumber.toString();
    
    if ($cell.text() !== newValue) {
      $cell.text(newValue)
        .removeClass('update-flash')
        .addClass('update-flash');
      
      // 用one方法自动移除事件监听,不用手动清理
      $cell.one('animationend webkitAnimationEnd oAnimationEnd', function() {
        $(this).removeClass('update-flash');
      });
    }
  });
}

setInterval(dataRenew, 2000);

jQuery的one方法会在事件触发一次后自动移除监听,省心又避免内存泄漏。

效果说明

每次API返回新数据且与当前单元格内容不同时,单元格会从红色平滑过渡到默认背景色,动画仅播放一次,完全匹配你的需求。

内容的提问来源于stack exchange,提问作者reaver lover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:27:32