js修改css屬性的方法:1、修改style樣式,語法“樣式表的指定內容.style.屬性="值"”;2、修改特定元素節(jié)點的style內容,語法“元素對象.style.cssText="樣式值"”;3、使用setAttribute()函數(shù)。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
原生JS修改CSS屬性有以下三種方法
-
修改style樣式
通過document.styleSheets[n] // n表示期望修改的樣式表序號,從0開始計數(shù)來獲取到期望修改的樣式表,通過cssRules[0]獲取到該樣式表的css內容,通過style修改特定樣式。(此方法比較麻煩,需要清楚指定樣式在樣式表的順序) -
修改特定元素節(jié)點的style內容
cssText可以一次性修改多個css屬性
style.attrName 修改單個屬性 attrName的值 -
通過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. 修改特定元素節(jié)點的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高級教程】