CSS Value Modification with JavaScript
JavaScript offers an easy way to set inline CSS values. However, this method can pose a challenge when modifying CSS values defined within stylesheets that are not inline.
Retrieving CSS Values from the Stylesheet
To retrieve CSS values that are not inline, JavaScript allows access to stylesheets through document.styleSheets. This function returns an array of all stylesheets in the document. To locate the specific stylesheet, use the document.styleSheets[styleIndex].href property.
Modifying Stylesheet CSS Rules
Once the desired stylesheet is identified, the next step is to obtain an array of CSS rules. This array is accessed using the rules property for Internet Explorer and cssRules for most other browsers. Each rule can be distinguished by its selectorText property.
To modify a CSS value, set the value property of the rule. The updated code would look similar to this:
<code class="javascript">var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex]; var selector = rule.selectorText; //maybe '#tId' var value = rule.value; //both selectorText and value are settable.</code>
This approach allows you to change CSS values globally, effectively updating all elements with the specified style.
The above is the detailed content of How Can I Modify CSS Values Defined in External Stylesheets Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!