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

如何检测DOM元素上发生变更的CSS style属性名,如backgroundColor、color等

检测DOM元素style变更并获取变化属性名的实现方案

实现逻辑

  • 给MutationObserver配置attributeFilter: ['style'],只监听元素的style属性变化,过滤其他无关属性的变更通知
  • 提前缓存元素的初始style属性集合,每次触发变更回调时,对比当前style集合和缓存的旧集合,找出值发生变化的属性名即可

完整代码

HTML部分

<h1 id="id1" style="background-color:green;color:blue;">My Heading 1</h1>
<button type="button" 
onclick="document.getElementById('id1').style.color = 'yellow'">
修改颜色
</button>
<button type="button" 
onclick="document.getElementById('id1').style.backgroundColor = 'red'">
修改背景色
</button>

JS部分

const observeEl = document.getElementById("id1");
// 工具函数:将元素style转为驼峰命名的键值对象,和JS操作style的属性名格式保持一致
function getStyleObj(el) {
  const styleObj = {};
  for (let i = 0; i < el.style.length; i++) {
    const prop = el.style[i];
    // 短横线命名转驼峰命名
    const camelProp = prop.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase());
    styleObj[camelProp] = el.style.getPropertyValue(prop);
  }
  return styleObj;
}
// 缓存元素初始style集合
let oldStyle = getStyleObj(observeEl);
const observerp = new MutationObserver(function() {
  const newStyle = getStyleObj(observeEl);
  const changedProps = [];
  // 筛选新增/值发生变更的属性
  for (const prop in newStyle) {
    if (newStyle[prop] !== oldStyle[prop]) {
      changedProps.push(prop);
    }
  }
  // 筛选被删除的属性
  for (const prop in oldStyle) {
    if (!(prop in newStyle)) {
      changedProps.push(prop);
    }
  }
  // 对变更属性去重
  const uniqueChangedProps = [...new Set(changedProps)];
  // 这里即可拿到所有发生变更的style属性名
  if (uniqueChangedProps.length) {
    alert("id1发生变化的style属性:" + uniqueChangedProps.join(','));
  }
  // 更新缓存的旧style集合,保证下次对比准确性
  oldStyle = newStyle;
});
// 不需要监听子树可以把subtree设为false,降低性能消耗
observerp.observe(observeEl, {attributes: true, attributeFilter: ['style'], subtree: false});

效果说明

点击修改颜色按钮会触发回调打印color,点击修改背景色按钮会触发回调打印backgroundColor,完全符合仅获取变更属性名的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 00:15:01