Summarize the method of reading and writing CSS style with JS

Source: Internet
Author: User

in order to facilitate future inquiries, I read some of the information summarized the following methods, if there is no place to welcome the point!  The CSS style of a document element can be read and written through a style object (that is, the Cssstyledeclaration object) of the DOM node object .such as: var elm = document.getElementById (' test ');Elm.style.color = ' black ';  Second, the GetAttribute (), SetAttribute (), RemoveAttribute () of the element object are read and written directly to the style propertysuch as: Elm. SetAttribute (' style ', ' color:red;line-height:30px ');   third, through the Cssstyledeclaration object csstext attribute and SetProperty (), Removeproperty and other methodssuch as: Elm.style. csstext =' color:red;line-height:30px '; Elm.style. Removeproperty (' color ');Elm.style. SetProperty (' Color ', ' green ', ' important ');Elm.style. Csstext = ";//quickly empty all claims for this rule The Style Declaration section of each CSS rule (the inner part of the brace) is a Cssstyledeclaration object whose properties and methods are:Properties:1.cssText: All style declaration text for the current rule. This property is read-write and can be used to set the current rule. 2.length: How many declarations the current rule contains. 3.parentRule: The rule that contains the current rule, the Parentrule property of the same Cssrule interface. Method:The 1.getPropertyPriority () method returns the priority of the specified declaration, or "important" if any, otherwise it is an empty string;The 2.getPropertyValue method returns the value of the specified declaration;the 3.item (index) method returns the property name at the specified position, and is generally more straightforward with the [index] syntax;The 4.removeProperty method is used to delete a CSS property and return the deleted value;The 5.setProperty method is used to set the specified CSS property, with no return value;  Use the Document.stylesheets property to return all Stylesheet objects of the current page (that is, all style sheets), which is a read-only class array object whose elements are Cssstylesheet objects ( Inherited from the Stylesheet object), the properties of the object are as follows:Properties:The 1.cssRules class array object, which is the CSS rule Cssstylerule object in the style sheet; IE9 follows the rules;The 2.disabled property is used to turn a style sheet on or off, with a value of true or disabled;The 3.ownerNode property returns the DOM node where the Stylesheet object is located, usually <link> or <style>. For style sheets that are referenced by other style sheets, this property is null;4. Because the CSS @import command allows other style sheets to be loaded in the stylesheet, there is the Parentstylesheet property, which returns the style sheet that includes the current style sheet. If the current style sheet is a top-level style sheet, the property returns null;The 5.type property returns the type value of the Stylesheet object, usually text/css;The 6.title property returns the title value of the Stylesheet object;The 7.href property is a read-only property that returns the style sheet address of the Stylesheet object connection. For an inline style node, this property is equal to null;The 8.media attribute indicates whether the style sheet is for screen, print, or both (all), the property is read-only, and the default value is screens;method:deleterule() Removes a rule from the style sheet,insertrule() Inserts a new rule into the style sheet, IE9 the following addrule (), Removerule ();such as: document. stylesheets [0]. Insertrule (' #test: hover{color:white;} ', 0);document. stylesheets [0].deleterule (0); Delete the first rule in a style sheetDocument.stylesheets[0]. Cssrules [1]. Selectortext; Returns the picker stringdocument.stylesheets[0].cssrules[1].csstext;//Returns a rule string with selectorsDocument.stylesheets[0].cssrules[1].style.border;document.stylesheets[0].cssrules[1].style.csstext;//Returns all style declaration strings for the current rule  v. Using the getComputedStyle method of the Window object, the first parameter is the element object, the second argument can be null, an empty string, a pseudo-element string, and the method returns a read-only The Cssstyledeclaration object representing the calculated style, which represents the final style information applied on the specified element , i.e. the result of the overlay of various CSS rules ;such as: var color = window.getComputedStyle (Elm, ': Before '). Color;var color = window.getComputedStyle (Elm, ': Before '). GetPropertyValue (' color ');or: var color = window.getComputedStyle (elm, null). Color; represents the difference between a Cssstyledeclaration object that evaluates a style and a Cssstyledeclaration object that represents an inline style:1. The properties of the calculated style are read-only;2. The value of the calculated style is absolute, and the relative units such as percentages and points are converted all to the absolute value of the string with the ' px ' suffix, whose value is the color of the property to be returned in the format "RGB (#,#,#)" or "Rgba (#,#,#,#)";3. Do not calculate composite attributes, only based on the most basic attributes, such as do not query margin, and separate query margintop, etc.;4. The calculated style object does not define the Csstext attribute;5. The calculation style is deceptive at the same time, it should be noted that the return value when querying some properties is not necessarily accurate, such as query font-family;6.IE9 below does not support the getComputedStyle method, ie's element object has currentstyle attribute;  Vi. Adding style sheets directly1. Create a label <style> add a built-in style sheetvar style1 = document.createelement (' style ');style1.innerhtml = ' body{color:red}#top: hover{background-color:red;color:white;}';Document.head.appendChild (style1);2. Another is to add an external style sheet that adds a link node to the document and then points the href attribute to the URL of the external style sheetvar link1 = document.createelement (' link ');link1.setattribute (' rel ', ' stylesheet ');link1.setattribute (' type ', ' text/css ');link1.setattribute (' href ', ' reset-min.css ');Document.head.appendChild (LINK1);  The Window.matchmedia method is used to check the Mediaquery statement of the CSS. The latest versions of various browsers (including IE + +) Support This method, for older browsers that do not support this method, you can use the third-party function library matchmedia.js;Here is an example of the Mediaquery statement:@media All and (max-device-width:700px) {Body {background: #FF0;}                }the Window.matchmedia method takes a string of mediaquery statements as a parameter and returns a Mediaquerylist object. The object has the following two properties: Media: Returns the queried Mediaquery statement string. matches: Returns a Boolean value that indicates whether the current environment matches the query statement.

var result = Window.matchmedia (' (max-width:700px) ');
if (result.matches) {
Console.log (' page width is less than or equal to 700px ');
} else {
Console.log (' page width greater than 700px ');

                }

The Mediaquerylist object returned by the Window.matchmedia method has two methods for listening to events: AddListener methods and RemoveListener methods. Invokes the specified callback function if the Mediaquery query result is changed;

var mql = Window.matchmedia ("(max-width:700px)");
Mql.addlistener (Mqcallback);//Specify callback function
Mql.removelistener (Mqcallback);//Undo callback function
function Mqcallback (MQL) {if (mql.matches) {//width less than or equal to 700 pixels}else {//width greater than 700 pixels}                }  This article refers to:Mdn:https://developer.mozilla.org/zh-cn/docs/web/apiNanyi JavaScript reference: http://javascript.ruanyifeng.com/dom/css.htmlJavaScript Definitive Guide Sixth edition 

Summarize the method of reading and writing CSS style with JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.