Home > Web Front-end > CSS Tutorial > How can I dynamically change CSS class rules in real time with jQuery?

How can I dynamically change CSS class rules in real time with jQuery?

Susan Sarandon
Release: 2024-11-03 10:35:02
Original
379 people have browsed it

How can I dynamically change CSS class rules in real time with jQuery?

Change CSS Class Rules Dynamically with jQuery

Your query involves two aspects:

1. Modifying Class Rules in Real Time

jQuery alone cannot alter CSS class rules dynamically. However, you can utilize the styleSheets property of the document object to access CSS rules directly.

Code:

<code class="javascript">document.getElementById("button").onclick = function() {
    var ss = document.styleSheets;

    for (var i = 0; i < ss.length; i++) {
        var rules = ss[i].cssRules;
        for (var j = 0; j < rules.length; j++) {
            if (rules[j].selectorText === ".classname") {
                rules[j].style.fontSize = "20px";
            }
        }
    }
};</code>
Copy after login

2. Saving Class Changes to File

To save class changes to a file, you need to extract the CSS rules and send them to the server via an Ajax request. The server-side implementation involves creating or updating a file with the modified rules.

Additional Notes:

  • For IE6 compatibility, use document.styleSheets instead of document.styleSheets.
  • To get the CSS rules, access the rules property of the stylesheet object.
  • Use the cssText property to set or modify CSS rules.

References:

  • document.styleSheets (Mozilla): https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets
  • styleSheet Object (Mozilla): https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet
  • CssRule Object (Mozilla): https://developer.mozilla.org/en-US/docs/Web/API/CSSRule
  • document.styleSheets (MSDN): https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/dom/document.stylesheets
  • CssRule Object (MSDN): https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/dom/cssrule

The above is the detailed content of How can I dynamically change CSS class rules in real time with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template