Home > Article > Web Front-end > How to modify css properties in js
JS method to modify css attributes: 1. Modify the style style, the syntax "specified content of the style sheet.style.Attribute="value""; 2. Modify the style content of a specific element node, the syntax "element object" .style.cssText="Style value""; 3. Use the setAttribute() function.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Modify style style
Through document.styleSheets[n] // n Represents the serial number of the style sheet that is expected to be modified. Counting starts from 0 to obtain the style sheet that is expected to be modified. The css content of the style sheet is obtained through cssRules[0], and the specific style is modified through style. (This method is more troublesome, and you need to clearly specify the order of the styles in the style sheet)
Modify the style content of a specific element node
cssText can be modified multiple times at one time css attributes
style.attrName Modify the value of a single attribute attrName
Modify the style attribute value through setAttribute
<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)
[Recommended learning: javascript advanced tutorial】
The above is the detailed content of How to modify css properties in js. For more information, please follow other related articles on the PHP Chinese website!