Summary of methods for reading and writing CSS styles by JS, and css styles read and write by js

Source: Internet
Author: User

Summary of methods for reading and writing CSS styles by JS, and css styles read and write by js

For future convenience, I have read some documents and summarized the following methods, only for native JS. If there is anything wrong, please point it out! After reading this, I think it's okay to learn something!

1. You can read and write CSS styles of document elements through the style object of the DOM Node object (that is, the CSSStyleDeclaration object ).
For example, var elm = document. getElementById ('test ');
Elm. style. color = 'black ';

2. Use getAttribute (), setAttribute (), and removeAttribute () of the Element object to directly read and write the style attribute.
For example, elm. setAttribute ('style', 'color: red; line-height: 30px ');

3. cssText attribute and setProperty () and removeProperty of the CSSStyleDeclaration object
For example:

Elm.style.css Text = 'color: red; line-height: 30px '; elm. style. removeProperty ('color'); elm. style. setProperty ('color', 'green', 'important'incluelm.style.css Text = ''; // quickly clear all declarations of the rule

The style declaration part of each CSS rule (the part inside the braces) is a CSSStyleDeclaration object. Its Attributes and methods are as follows:
Attribute:
1. cssText: All style declaration texts of the current rule. This attribute can be read and written to set the current rule.
2. length: the number of statements contained in the current rule.
3. parentRule: the rule that contains the current rule, which is the same as the parentRule attribute of the CSSRule interface.
Method:
1. The getPropertyPriority () method returns the priority of the specified declaration. If yes, it is "important"; otherwise, it is a null string;
2. The getPropertyValue method returns the specified declared value;
3. The item (index) method returns the attribute name at the specified position. Generally, the [index] syntax is more direct;
4. The removeProperty method is used to delete a CSS attribute and return the deleted Value;
5. The setProperty method is used to set the specified CSS attribute without returning a value;

4. Using the document. styleSheets attribute,Returns all StyleSheet objects (all style sheets) on the current page. It is a read-only array object, and its elements are CSSStyleSheet objects (inherited from StyleSheet objects ), the attributes of this object are as follows:
Attribute:
1.css Rules array object. The elements are CSS rule CSSStyleRule objects in the style sheet; rules is lower than IE9;
2. The disabled attribute is used to open or close a style sheet. The value is true or disabled;
3. The ownerNode attribute returns the DOM node where the StyleSheet object is located, usually <link> or <style>. This attribute is null for style sheets referenced by other style sheets;
4. Because the @ import command of CSS allows loading other style sheets in the style sheet, the parentStyleSheet attribute is available. It returns the style sheet containing the current style table. If the current style table is a top-level style table, null is returned for this attribute;
5. The type attribute returns the type value of the StyleSheet object, usually text/css;
6. The title attribute returns the title value of the StyleSheet object;
7. The href attribute is read-only and returns the style table address connected to the StyleSheet object. For nested style nodes, this attribute is equal to null;
8. The media attribute indicates whether the style sheet is used for screen, print, or all. This attribute is read-only and the default value is screen;
Method: deleteRule () deletes a rule from the style sheet. insertRule () inserts a new rule into the style sheet. The rules below IE9 are addRule () and removeRule ();
For example:

Document. styleSheets [0]. insertRule ('# test: hover {color: white;}', 0); document. styleSheets [0]. deleteRule (0); // Delete the first rule in the style sheet document.stylesheets%0%.css Rules [1]. selectorText; // return the selector string document.stylesheets%0}.cssrules%1}.css Text; // return the rule string, including the selector document.stylesheets%0}.css Rules [1]. style. border; document.stylesheets%0%.cssrules%1%.style.css Text; // return all style declaration strings of the current rule

5. Use the getComputedStyle method of the window object,The first parameter is an Element object. The second parameter can be a null, null string, or pseudo Element string. This method returns a read-only CSSStyleDeclaration object that represents the computing style, it represents the final style information applied to a specified element, that is, the result of the superposition of various CSS rules;

For example, var color = window. getComputedStyle (elm, ': before'). color;
Var color = window. getComputedStyle (elm, ': before'). getPropertyValue ('color ');
Or: var color = window. getComputedStyle (elm, null). color;

The difference between a CSSStyleDeclaration object that represents a calculation style and a CSSStyleDeclaration object that represents an inline style:
1. the attribute of the calculated style is read-only;
2. the calculated value of the style is the absolute value. units such as percentages and vertices are all converted to the absolute value of the string suffixed with 'px, the value of the color attribute is returned in the format of "rgb (#, #, #)" or "rgba;
3. The composite attributes are not calculated. They are only based on the basic attributes, such as querying margin instead of marginTop separately;
4. The cssText attribute is not defined for the calculation style object;
5. computation styles are also fraudulent. When using them, you must note that the returned values for certain attributes are not necessarily accurate, such as font-family;
6. The getComputedStyle method is not supported below IE9. The Element Object of IE has the currentStyle attribute;

6. Add a style sheet directly
1. Create a label <style> Add a built-in style sheet

var style1 = document.createElement('style'); style1.innerHTML = 'body{color:red}#top:hover{background-color: red;color: white;}'; document.head.appendChild(style1);

2. Add an external style sheet, that is, add a link node to the document, and then direct the href attribute to the URL of the external style sheet.

var link1 = document.createElement('link');link1.setAttribute('rel', 'stylesheet');link1.setAttribute('type', 'text/css');link1.setAttribute('href', 'reset-min.css');document.head.appendChild(link1);

7. The window. matchMedia method is used to check the mediaQuery statements of CSS.The latest versions of various browsers (including IE 10 +) support this method. For older browsers that do not support this method, you can use the third-party function library matchMedia. js;
The following is an example of the mediaQuery statement:

 @media all and (max-device-width: 700px) {           body {background: #FF0;}         } 

The window. matchMedia method accepts the string of A mediaQuery statement as the parameter and returns a MediaQueryList object. This object has the following attributes:
Media:Returns the queried mediaQuery statement string.
Matches:Returns a Boolean value indicating whether the current environment matches the query statement.

Var result = window. matchMedia ('(max-width: 700px)'); if (result. matches) {console. log ('page width 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 to listen to events: the addListener method and the removeListener method. If the mediaQuery query result changes, the specified callback function is called;

Var mql = window. matchMedia ("(max-width: 700px)"); mql. addListener (mqCallback); // specify the mql callback function. removeListener (mqCallback); // undo the callback function mqCallback (mql) {if (mql. matches) {// The width is less than or equal to 700 pixels} else {// The width is greater than 700 pixels }}

Reference:
MDN: https://developer.mozilla.org/zh-CN/docs/Web/API
Ruan Yifeng javascript reference: http://javascript.ruanyifeng.com/dom/css.html
Javascript authoritative guide version 6

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.