原生JS修改CSS属性

原生JS修改CSS属性有以下三种方法

  1. 修改style样式
    通过document.styleSheets[n] // n表示期望修改的样式表序号,从0开始计数来获取到期望修改的样式表,通过cssRules[0]获取到该样式表的css内容,通过style修改特定样式。(此方法比较麻烦,需要清楚指定样式在样式表的顺序)
  2. 修改特定元素节点的style内容
    cssText可以一次性修改多个css属性
    style.attrName 修改单个属性 attrName的值
  3. 通过setAttribute 修改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>


CSS代码
.test {
    
    
   font-size: 30px;
   color: blue;
   background-color: blueviolet
}

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)

猜你喜欢

转载自blog.csdn.net/weixin_43757001/article/details/98636990
今日推荐