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

如何通过点击按钮移除全站CSS中的content属性

点击按钮移除全站CSS的content属性

原来的代码仅移除了第一个样式表第一条规则的content属性,要实现全站范围的移除效果,需要遍历页面中所有样式表,再逐一处理每个样式表内的所有CSS规则,将包含content属性的规则全部移除该属性。

完整代码实现

HTML

<button onclick="removeAllContentProperties()">删除content属性</button>

<img src="https://m.media-amazon.com/images/I/81K2hJBAduL.png">
<p>测试段落</p>
<div>测试容器</div>

CSS(示例样式)

img {
  content: url("https://static.vecteezy.com/system/resources/previews/005/476/277/original/under-18-forbidden-round-icon-sign-illustration-eighteen-or-older-persons-adult-content-18-plus-only-rating-isolated-on-white-background-free-vector.jpg");
  max-width: 100%;
  height: auto;
}

p::before {
  content: "前缀文本: ";
  color: red;
}

div::after {
  content: "后缀文本";
  color: blue;
}

JavaScript

function removeAllContentProperties() {
  // 遍历页面中所有样式表
  for (const styleSheet of document.styleSheets) {
    try {
      // 遍历当前样式表的所有CSS规则
      for (const rule of styleSheet.cssRules) {
        // 检查规则是否包含可操作的样式声明,且存在content属性
        if (rule.style && rule.style.getPropertyValue('content')) {
          rule.style.removeProperty('content');
        }
      }
    } catch (e) {
      // 捕获跨域样式表的访问错误(浏览器同源策略限制)
      console.log('无法访问跨域样式表:', styleSheet.href);
    }
  }
}

逻辑说明

  • 通过document.styleSheets获取页面所有样式表,涵盖内嵌样式、本地外联样式和部分同域外联样式
  • 遍历样式表时添加try-catch,避免跨域样式表的访问报错中断整个移除流程
  • 对每个CSS规则,判断其样式声明中是否存在content属性,存在则调用removeProperty完成移除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:02:28