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

使用JavaScript的setProperty修改CSS样式时遇只读错误求助

解决getComputedStyle调用setProperty报错的问题

你遇到的错误核心原因是:window.getComputedStyle()返回的是元素计算后的最终样式,这类样式属于只读属性,无法通过setProperty直接修改。

正确的修改方式有两种:

方式1:直接操作元素的内联样式

通过元素的style属性(这是可写的CSSStyleDeclaration对象)来修改样式,代码调整如下:

function click1() {
  var para = document.querySelector('h1');
  // 仅用计算样式获取当前值用于展示
  var computedStyle = window.getComputedStyle(para);
  var colorValue = computedStyle.getPropertyValue('color');
  document.getElementById('a').innerHTML = colorValue;
  // 修改内联样式改变颜色
  para.style.setProperty('color', 'red');
}

方式2:通过CSS类修改样式(更推荐)

这种方式符合样式与逻辑分离的原则,便于维护和复用:

  1. 先补充CSS类:
h1 {
  color: rgb(77, 50, 130);
}
h1.red-text {
  color: red;
}
  1. 调整JS代码:
function click1() {
  var para = document.querySelector('h1');
  var computedStyle = window.getComputedStyle(para);
  var colorValue = computedStyle.getPropertyValue('color');
  document.getElementById('a').innerHTML = colorValue;
  // 添加类来应用红色样式
  para.classList.add('red-text');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:34:54