王新阳

wangxinyang

使用原生JS修改css属性

修改style样式:
1. 通过document.styleSheets[n] // n表示期望修改的样式表序号,从0开始计数来获取到期望修改的样式表,通过cssRules[0]获取到该样式表的css内容,通过style修改特定样式;
2. 修改特定元素节点的style内容cssText可以一次性修改多个css属性style.attrName 修改单个属性 attrName的值
3. 通过setAttribute 修改style属性值

<style>
.test {font-size: 30px;color: blue;background-color: blueviolet}
</style>
// html
<div class="test" style="height: 100px;">TEST</div>
<button class="cssText">cssText</button>
<button class="setAttribute">setAttribute</button>
<button class="stylesheet ">stylesheet </button>
// js
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);


2019-10-15
2024-05-01 星期三 农历三月二十三