如何使用JavaScript修改嵌入式CSS中的样式规则
JavaScript修改嵌入式CSS样式的实现方法
有两种常用的实现方案,都可以满足需求:
方法1:直接修改style标签文本内容
操作最简单,适合快速修改全量样式,或者仅修改单条规则的场景:
- 如果可以覆盖style标签内所有原有样式,直接重写文本:
// 定位到目标style标签,建议给对应style加唯一id比如id="customStyle",使用querySelector('#customStyle')匹配更精准 const styleElement = document.querySelector('style'); styleElement.textContent = ` .middleBTN { background-color: blue; } `;
- 如果需要保留style标签内其他原有样式,只修改目标规则,使用字符串替换即可:
const styleElement = document.querySelector('style'); styleElement.textContent = styleElement.textContent.replace('background-color:red;', 'background-color:blue;');
方法2:通过CSSStyleSheet API精准修改规则
不需要重写整个style标签内容,直接操作样式规则对象,稳定性和性能更好:
// 获取页面所有样式表 const allStyleSheets = document.styleSheets; // 定位到目标嵌入式样式表,索引对应页面中style标签的顺序,第一个style索引为0 const targetSheet = allStyleSheets[0]; // 遍历样式表的所有规则,匹配目标选择器 for (let i = 0; i < targetSheet.cssRules.length; i++) { const currentRule = targetSheet.cssRules[i]; if (currentRule.selectorText === '.middleBTN') { // 普通修改 currentRule.style.backgroundColor = 'blue'; // 如果原有样式带!important标识,用下方写法覆盖 // currentRule.style.setProperty('background-color', 'blue', 'important'); break; } }
注意事项
- 页面存在多个style标签时,给目标style添加唯一id可以完全避免匹配错误
- 修改带
!important标识的样式时,必须使用setProperty方法传入第三个参数important才能生效
内容的提问来源于stack exchange,提问作者JayCee
相关产品推荐
相关产品推荐

