Use JavaScript to create new style sheets and new style rules, JavaScript style sheets
In this age, the popularity of Web pages using a lot of JavaScript, we need to find a variety of ways to optimize them, make them faster. We use event delegates to make event listeners more efficient, use frequency reduction techniques to limit the number of uses of certain methods, use various JavaScript loaders to dynamically load the resources we need, and so on. Another way to make the page more efficient and agile is to dynamically add or remove styles from the stylesheet without having to query DOM elements and make a style adjustment for each element. Let's take a look at how to use this technology!
Capturing style Sheets
More than one style file may be referenced on your page, and you can choose one of them. If you specify something, you can make a difference by adding an ID to the link and style tag in the HTML page to get the Cssstylesheet object, which is stored in the Document.stylesheets object.
var sheets = document.stylesheets; Returns an Stylesheetlist array/* returned: stylesheetlist {0:cssstylesheet, 1:cssstylesheet, 2:cssstylesheet, 3:cssstylesheet, 4:cs Sstylesheet, 5:cssstylesheet, 6:cssstylesheet, 7:cssstylesheet, 8:cssstylesheet, 9:cssstylesheet, 10:cssstylesheet, 11:cssstylesheet, 12:cssstylesheet, 13:cssstylesheet, 14:cssstylesheet, 15:cssstylesheet, Length:16, item:function} *///Find the style sheet you want to modify var sheet = document.stylesheets[0];
One important thing to be aware of is the media properties of the stylesheet--if you're not careful, you might incorrectly modify the style sheet used for printing (print) When you want to make changes to the style table that you're using on the screen. The Cssstylesheet object has various property information that you can get from it when needed.
Get info about the first stylesheetconsole.log (Document.stylesheets[0]);/* return result: Cssstylesheet cssrules:cssrulelist Disabled:false href: "http://davidwalsh.name/somesheet.css" Media:medialist ownernode:link ownerrule:null Parentstylesheet:null rules:cssrulelist title:null Type: "Text/css" *///Get the media typeconsole.log (Document.stylesh Eets[0].media.mediatext)/*returns: "All" or "print" or whichever media are used for this stylesheet*/
There are a number of ways you can capture a style sheet and add new style rules to it.
Create a new style sheet
Most of the time, the best way is to create a new style element that dynamically adds rules to it. Very simple:
var sheet = (function () {//Create the