


Let'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:
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:
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:
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.
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))
}
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
