js修改css属性的方法:1、修改style样式,语法“样式表的指定内容.style.属性="值"”;2、修改特定元素节点的style内容,语法“元素对象.style.cssText="样式值"”;3、使用setAttribute()函数。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
修改style样式
通过document.styleSheets[n] // n表示期望修改的样式表序号,从0开始计数来获取到期望修改的样式表,通过cssRules[0]获取到该样式表的css内容,通过style修改特定样式。(此方法比较麻烦,需要清楚指定样式在样式表的顺序)
修改特定元素节点的style内容
cssText可以一次性修改多个css属性
style.attrName 修改单个属性 attrName的值
通过setAttribute 修改style属性值
立即学习“前端免费学习笔记(深入)”;
<div class="test" style="height: 100px;">TEST</div> <button class="cssText">cssText</button> <button class="setAttribute">setAttribute</button> <button class="stylesheet ">stylesheet </button>
.test {
font-size: 30px;
color: blue;
background-color: blueviolet
} var testNode = document.getElementsByClassName("test")[0];
var cssTextBtn = document.getElementsByClassName("cssText")[0];
var attributeBtn = document.getElementsByClassName("setAttribute")[0];
var stylesheetBtn = document.getElementsByClassName("stylesheet")[0];
// 1. 修改style样式:
stylesheetBtn.addEventListener('click', function(e) {
var stylesheet = document.styleSheets[0];
stylesheet.cssRules[0].style.backgroundColor = "green";
}, false);
// 2. 修改特定元素节点的style内容
cssTextBtn.addEventListener('click', function(e) {
testNode.style.cssText = "width: 300px; background-color: red; height: 200px;"
testNode.style.border = "1px solid black"
}, true);
// 3. 通过setAttribute 修改style属性值
attributeBtn.addEventListener('click', function(e) {
testNode.setAttribute('style', 'width: 400px; background-color: yellow; height: 300px;')
}, false)【推荐学习:javascript高级教程】
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号