欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

玩转原生JS:如何轻松修改CSS属性?

最编程 2024-08-10 12:09:20
...

原生JS——修改css属性

  1. 修改style样式:
    通过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)

©著作权归作者所有,转载或内容合作请联系作者

推荐阅读