Home >Web Front-end >JS Tutorial >How can I dynamically change CSS values defined in a stylesheet using Javascript?

How can I dynamically change CSS values defined in a stylesheet using Javascript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 02:32:27354browse

How can I dynamically change CSS values defined in a stylesheet using Javascript?

Changing CSS Values with Javascript: Understanding Stylesheet Manipulation

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:

  • It affects only inline values.
  • Retrieving the width value before modifying it returns Null when there's no inline style.

Solution: Manipulating Stylesheet Values

To address these challenges, we need to manipulate values directly in the stylesheet. Here's how it can be achieved:

  1. Get an array of stylesheets using document.styleSheets.
  2. Find the specific stylesheet you want to modify using document.styleSheets[styleIndex].href.
  3. Get an array of CSS rules using document.styleSheets[styleIndex].cssRules (for most browsers) or document.styleSheets[styleIndex].rules (for IE).
  4. Identify the CSS rule you want to change by checking the selectorText property.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn