search
HomeWeb Front-endJS TutorialLet's talk about javascript dynamically adding style rules W3C check_javascript skills

There is no doubt that based on the principle of separation of performance and structure, directly importing a new style sheet is the best choice, but in some cases it will not work. For example, if we make a draggable DIV, from the perspective of setting styles, it is Position it absolutely to prevent it from affecting the original document flow, and then change its top and left values ​​little by little to achieve the effect of movement. Since dragging has a time concept, 24 frames per second, it is impossible to include everything in the style sheet. Therefore, it is very necessary to dynamically generate style rules and quickly modify style rules. W3C has done a lot of work for this. In DOM2.0, many interfaces have been expanded.

Taking a step back, the separation of performance and structure is not limited to importing style sheets. You know, there are three types of styles, external styles, internal styles, and inline styles.

* External style, the one we mentioned above, is written in a separate CSS file.
* Internal style is written independently in a style tag, usually placed in the head tag. The style generated by the last function I provided is the internal style.
* Inline style is the style written in the style attribute of the element.

The newly added interfaces are mainly concentrated in external styles - I say interfaces because the corresponding implementations are provided by the browser. Arrogant guys like IE6 never ignore their existence.

In the W3C model, the link tag and style tag of type "text/css" both represent a CSSStyleSheet object. We can obtain all CSSStyleSheet objects in the current page through document.styleSheets, but this is A collection, not a simple array. Each CSSStyleSheet object has the following properties,

* type: always returns "text/css" string.
* disabled: has the same effect as input's disabled, and the default is false.
* href: Returns the URL, if the style tag is null.
* title: Returns the value of its title. The title is the same as the title of an ordinary element. You can write whatever you like.
* media: The things returned by IE and Firefox are not consistent, so it’s hard to say. media is used to specify which devices the style rules it owns are valid for. The default is all.
* ownerRule: Returns a read-only CSSRule object if the style sheet is introduced with @import.
* cssRules: Returns a collection of read-only style rule objects (CSSStyleRule objects).

The CSSStyleRule object is created by W3C in order to set the style in more detail. For example, the following thing corresponds to a style rule object:

Copy code The code is as follows:

button[type] {
padding:4px 10px 4px 7px;
line-height :17px;
}

The style rule object has the following main attributes: type, cssText, parentStyleSheet, parentRule.

type is somewhat similar to nodeType, which subdivides style rules. It uses an integer to represent its type. The specific situation is as follows

* 0: CSSRule.UNKNOWN_RULE
* 1: CSSRule.STYLE_RULE (define a CSSStyleRule object)
* 2: CSSRule.CHARSET_RULE (define a CSSCharsetRule object for setting the current The character set of the style sheet is the same as the current web page by default)
* 3: CSSRule.IMPORT_RULE (define a CSSImportRule object, which is to use @import to introduce other style sheets)
* 4: CSSRule.MEDIA_RULE (define a CSSMediaRule Object, used to set whether this style is used for monitors, printers, projectors, etc.)
* 5: CSSRule.FONT_FACE_RULE (define a CSSFontFaceRule object, @font-face of CSS3)
* 6: CSSRule. PAGE_RULE (define a CSSPageRule object)

Needless to say, cssText is a very useful attribute that directly converts strings into style rules, ignoring the differences in style attributes of each browser, such as cssFloat and styleFloat.

parentStyleSheet and parentRule are both for @import. However, @import has problems under IE, so I basically don’t use it.

There are a few unexpected methods:

* nsertRule(rule,index): Add a style rule.
* deleteRule(index): Remove a style rule.
* getPropertyValue(propertyName) Gets the value of the corresponding style attribute of the element. If we obtain a style rule object, we can use CSSStyleRuleObject.getPropertyValue("color") to obtain its font color setting. Compared with the ordinary el.style.color method, its efficiency is quite high, because el.style.color obtains the inline style. Freaks like IE cannot get it at all if your element does not set the style attribute. The prepared value may be empty, it may be inherit... there may be compatibility issues, and this inline attribute is not necessarily the style ultimately applied to the element. IE can only call the less useless el.currentStyle[prop], other browsers The processor calls document.defaultView.getComputedStyle(el, "")[prop] which is quite impressive but a bit cumbersome.
* removeProperty(propertyName) removes the corresponding style attribute of the element.
* setProperty(propertyName, value, priority) sets the element to add a style and also specifies the priority.

We can get a function to set the style:
Copy the code The code is as follows:

var hyphenize =function(name){
return name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
}

var camelize = function(name){
return name.replace(/-(w)/g, function(all, letter){
return letter.toUpperCase();
});
}
var setStyle = function(el, styles) {
for (var property in styles) {
if(!styles.hasOwnProperty(property)) continue;
if(el.style.setProperty ) {
//Must be a hyphen style, el.style.setProperty('background-color','red',null);
el.style.setProperty(hyphenize(property),styles[property] ,null);
} else {
//Must be camel case style, such as el.style.paddingLeft = "2em"
el.style[camelize(property)] = styles[property]
}
}
return true;
}

Usage:
Copy code The code is as follows:

setStyle(div,{
'left':0,
'top':0,
'line-height':'2em' ,
'padding-right':'4px'
});

But I don’t like this method very much. It generates inline styles, and it has to deal with float and opacity. In the inline style of IE7, there is a bug in the filter. You must let it get hasLayout, otherwise the filter will not take effect (we can check its status through el.currentStyle.hasLayout). Therefore, instead of setting them one by one, it is better to use cssText to catch them all.

Finally, I attach my enhanced version of the addSheet method. It adds the function of automatically processing opacity, which means that we only need to set the cssText according to the standard, and it will automatically generate the corresponding filter. This will at least allow browsers such as Firefox to pass the W3C inspection.
Copy code The code is as follows:

var addSheet = function(){
var doc,cssCode;
if(arguments.length == 1){
doc = document;
cssCode = arguments[0]
}else if(arguments.length == 2){
doc = arguments[0];
cssCode = arguments[1];
}else{
alert("addSheet function has the most Accepts two parameters!");
}
if(! "v1"){//New function, users only need to enter the W3C transparent style, and it will automatically convert into IE's transparent filter
var t = cssCode.match(/opacity:(d?.d );/);
if(t!= null){
cssCode = cssCode.replace(t[0], "filter:alpha (opacity=" parseFloat(t[1]) * 100 ");");
}
}
cssCode = cssCode "n";//Add a newline character at the end to facilitate firebug Check.
var headElement = doc.getElementsByTagName("head")[0];
var styleElements = headElement.getElementsByTagName("style");
if(styleElements.length == 0){//if not If the style element exists, create
if(doc.createStyleSheet){ //ie
doc.createStyleSheet();
}else{
var tempStyleElement = doc.createElement('style');// w3c
tempStyleElement.setAttribute("type", "text/css");
headElement.appendChild(tempStyleElement);
}
}
var styleElement = styleElements[0];
var media = styleElement.getAttribute("media");
if(media != null && !/screen/.test(media.toLowerCase()) ){
styleElement.setAttribute("media"," screen");
}
if(styleElement.styleSheet){ //ie
styleElement.styleSheet.cssText = cssCode;//Add new internal style
}else if(doc.getBoxObjectFor) {
styleElement.innerHTML = cssCode;//Firefox supports adding style sheet strings directly to innerHTML
}else{
styleElement.appendChild(doc.createTextNode(cssCode))
}
}
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.