Home >Web Front-end >JS Tutorial >How can I dynamically change CSS values defined in a stylesheet using Javascript?
Often, we find the need to modify CSS values dynamically using Javascript. While setting inline CSS values is straightforward, it can present challenges when the CSS is defined in a stylesheet.
Example:
Consider the following HTML code:
<code class="html"><div id="tId" style="width: 10px"></div></code>
And the corresponding CSS:
<code class="css">#tId { width: 50%; }</code>
Modifying the inline style attribute using Javascript will override the stylesheet values, as seen below:
document.getElementById('tId').style.width = "30%";
This results in:
<code class="html"><div id="tId" style="width: 30%"></div></code>
Challenge:
The problem with this approach is that:
Solution: Manipulating Stylesheet Values
To address these challenges, we need to manipulate values directly in the stylesheet. Here's how it can be achieved:
The following code demonstrates this approach:
var styleIndex = ...; // Index of the targeted stylesheet var ruleIndex = ...; // Index of the targeted CSS rule var cssRuleCode = document.all ? 'rules' : 'cssRules'; var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex]; var value = rule.value; // Get the current value rule.value = ...; // Modify the value
By implementing this approach, you can effectively manipulate CSS values in stylesheets, ensuring that the changes are applied globally to all elements of the specified style.
The above is the detailed content of How can I dynamically change CSS values defined in a stylesheet using Javascript?. For more information, please follow other related articles on the PHP Chinese website!