Dynamic CSS Rule Creation and Reusability with jQuery
When working with CSS, it is often convenient to define static rules within a CSS file. However, there may be instances where you wish to add CSS information dynamically during runtime. This article explores how to create reusable CSS rules using jQuery, eliminating the need for multiple additions to specific DOM elements.
Creating a CSS Rule at Runtime
To create a CSS rule dynamically using jQuery, you can employ the following steps:
Create a style element using HTML markup:
<style type="text/css"></style>
Define the CSS rule within the style element:
.redbold { color: #f00; font-weight: bold; }
Append the style element to the document's head:
$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
Reusing the Created Rule
Once the CSS rule has been created, you can reuse it by applying the appropriate class to HTML elements:
<div class="redbold">SOME NEW TEXT</div>
$("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");
Compatibility
This method of creating and reusing CSS rules has been tested and confirmed to work in browsers such as Opera 10, Firefox 3.5, Internet Explorer 8, and Internet Explorer 6.
The above is the detailed content of How Can jQuery Be Used to Create and Reuse Dynamic CSS Rules?. For more information, please follow other related articles on the PHP Chinese website!