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

如何获取DOM元素的全部CSS样式?无需逐个指定属性名

解决方案

场景1:获取元素最终生效的所有样式

直接用浏览器原生window.getComputedStyle API即可,无需逐个枚举CSS属性,也不依赖内联样式或attr方法,会自动返回所有应用在元素上的最终生效样式(包含!important规则、继承样式、浏览器默认样式)。

原生JS实现代码:

// 选中应用了.filter类的目标元素
const targetEl = document.querySelector('.filter');
// 获取计算后样式集合
const computedStyle = window.getComputedStyle(targetEl);
// 转为普通JS对象方便读取操作
const allStyles = {};
for (let i = 0; i < computedStyle.length; i++) {
  const propName = computedStyle[i];
  allStyles[propName] = computedStyle.getPropertyValue(propName);
}

// 输出所有样式
console.log(allStyles);

jQuery封装实现:

你可以封装一个jQuery扩展方法,直接调用即可拿到所有样式:

// 注册jQuery扩展方法
$.fn.getFullStyles = function () {
  if (!this.length) return {};
  const computed = window.getComputedStyle(this[0]);
  return Array.from(computed).reduce((res, prop) => {
    res[prop] = computed.getPropertyValue(prop);
    return res;
  }, {});
};

// 调用示例
const filterStyles = $('.filter').getFullStyles();
console.log(filterStyles);

场景2:仅获取.filter类本身定义的样式

如果你不需要浏览器默认样式、其他类叠加的样式,只需要.filter类选择器下定义的所有规则,可以遍历样式表提取:

const filterClassRules = {};
Array.from(document.styleSheets).forEach(sheet => {
  try {
    // 跳过跨域无法访问的样式表
    Array.from(sheet.cssRules || sheet.rules).forEach(rule => {
      // 匹配.filter类选择器
      if (rule.selectorText?.trim() === '.filter') {
        Array.from(rule.style).forEach(prop => {
          filterClassRules[prop] = rule.style.getPropertyValue(prop);
          // 可以额外获取是否有!important标记
          filterClassRules[`${prop}!important`] = rule.style.getPropertyPriority(prop) === 'important';
        });
      }
    });
  } catch (err) {}
});

console.log(filterClassRules);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:48:01