CSS operations

CSS operations

CSS and JavaScript are two areas with a clear division of labor. The former is responsible for the visual effects of the page, and the latter is responsible for the interaction with the user's behavior. However, they belong to the front-end of web development after all, so they inevitably overlap and cooperate with each other. This chapter introduces how to manipulate CSS through JavaScript.

HTML element style attribute

The easiest way to manipulate CSS styles is to use the getAttribute() method, setAttribute() method and removeAttribute() method of web page element nodes to directly read and write or delete the style attributes of web page elements.

div.setAttribute("style", "background-color:red;" + "border:1px solid black;");

The above code is equivalent to the following HTML code.

<div style="background-color:red; border:1px solid black;" />

style can not only use string to read and write, it is also an object itself, deploying the CSSStyleDeclaration interface (see the introduction below), you can directly read and write individual properties.

e.style.fontSize = "18px";
e.style.color = "black";

CSSStyleDeclaration interface

Introduction

The CSSStyleDeclaration interface is used to manipulate the style of an element. This interface is deployed in three places.

-The style property of the element node (Element.style) -style property of CSSStyle instance -The return value of window.getComputedStyle()

The CSSStyleDeclaration interface can directly read and write CSS style attributes, but the hyphen needs to be changed into camel spelling.

var divStyle = document.querySelector("div").style;

divStyle.backgroundColor = "red";
divStyle.border = "1px solid black";
divStyle.width = "100px";
divStyle.height = "100px";
divStyle.fontSize = "10em";

divStyle.backgroundColor; // red
divStyle.border; // 1px solid black
divStyle.height; // 100px
divStyle.width; // 100px

In the above code, the value of the style property is an instance of CSSStyleDeclaration. The properties contained in this object correspond to the CSS rules one-to-one, but the name needs to be rewritten, for example, background-color is written as backgroundColor. The rule for rewriting is to remove the horizontal bar from the CSS property name, and then capitalize the first letter after the horizontal bar. If the CSS property name is a JavaScript reserved word, the string css must be added before the rule name, for example, float is written as cssFloat.

Note that the attribute values ​​of this object are all strings, and the unit must be included when setting, but the semicolon at the end of the rule is not included. For example, divStyle.width cannot be written as 100, but as 100px.

In addition, Element.style returns only inline styles, not all styles of the element. The style set through the style sheet, or the style inherited from the parent element, cannot be obtained through this attribute. All styles of the element should be obtained through window.getComputedStyle().

CSSStyleDeclaration instance properties

(1) CSSStyleDeclaration.cssText

The CSSStyleDeclaration.cssText property is used to read and write all style declaration texts of the current rule.

var divStyle = document.querySelector("div").style;

divStyle.cssText =
  "background-color: red;" +
  "border: 1px solid black;" +
  "height: 100px;" +
  "width: 100px;";

Note that the property value of cssText does not need to rewrite the CSS property name.

The easiest way to delete all inline styles of an element is to set cssText to an empty string.

divStyle.cssText = "";

(2) CSSStyleDeclaration.length

The CSSStyleDeclaration.length property returns an integer value indicating how many style declarations the current rule contains.

// HTML code is as follows
// <div id="myDiv"
// style="height: 1px;width: 100%;background-color: #CA1;"
// ></div>
var myDiv = document.getElementById("myDiv");
var divStyle = myDiv.style;
divStyle.length; // 3

In the above code, the inline style of the myDiv element contains a total of 3 style rules.

(3) CSSStyleDeclaration.parentRule

The CSSStyleDeclaration.parentRule property returns the style block (CSSRule instance) to which the current rule belongs. If there is no style block to which it belongs, this attribute returns null.

This property is read-only and only meaningful when using the CSSRule interface.

var declaration = document.styleSheets[0].rules[0].style;
declaration.parentRule === document.styleSheets[0].rules[0];
// true

CSSStyleDeclaration instance method

(1) CSSStyleDeclaration.getPropertyPriority()

The CSSStyleDeclaration.getPropertyPriority method accepts the property name of the CSS style as a parameter and returns a string indicating whether the important priority is set. If there is, return important, otherwise return an empty string.

// HTML code is
// <div id="myDiv" style="margin: 10px!important; color: red;"/>
var style = document.getElementById("myDiv").style;
style.margin; // "10px"
style.getPropertyPriority("margin"); // "important"
style.getPropertyPriority("color"); // ""

In the above code, the margin attribute has the priority of important, but the color attribute does not.

(2) CSSStyleDeclaration.getPropertyValue()

The CSSStyleDeclaration.getPropertyValue method accepts the CSS style property name as a parameter and returns a string representing the property value of the property.

// HTML code is
// <div id="myDiv" style="margin: 10px!important; color: red;"/>
var style = document.getElementById("myDiv").style;
style.margin; // "10px"
style.getPropertyValue("margin"); // "10px"

(3) CSSStyleDeclaration.item()

The CSSStyleDeclaration.item method accepts an integer value as a parameter and returns the CSS property name at that position.

// HTML code is
// <div id="myDiv" style="color: red; background-color: white;"/>
var style = document.getElementById("myDiv").style;
style.item(0); // "color"
style.item(1); // "background-color"

In the above code, the CSS property name at position 0 is color, and the CSS property name at position 1 is background-color.

If no parameters are provided, this method will report an error. If the parameter value exceeds the actual number of attributes, this method returns a null character value.

(4) CSSStyleDeclaration.removeProperty()

The CSSStyleDeclaration.removeProperty method accepts a property name as a parameter, removes this property from the CSS rules, and returns the original value of this property.

// HTML code is
// <div id="myDiv" style="color: red; background-color: white;">
// 111
// </div>
var style = document.getElementById("myDiv").style;
style.removeProperty("color"); //'red'
// HTML code becomes
// <div id="myDiv" style="background-color: white;">

In the above code, after deleting the color attribute, the font color changes from red to the default color.

(5) CSSStyleDeclaration.setProperty()

The CSSStyleDeclaration.setProperty method is used to set new CSS properties. This method has no return value.

The method can accept three parameters.

-The first parameter: the attribute name, this parameter is required. -The second parameter: attribute value, this parameter is optional. If omitted, the parameter value defaults to an empty string. -The third parameter: priority, this parameter is optional. If set, the only legal value is important, which means !important in CSS rules.

// HTML code is
// <div id="myDiv" style="color: red; background-color: white;">
// 111
// </div>
var style = document.getElementById("myDiv").style;
style.setProperty("border", "1px solid blue");

After the above code is executed, the myDiv element will appear with a blue border.

CSS module detection

The specifications of CSS are evolving too fast, and new modules are emerging in endlessly. Different versions of different browsers have different support for CSS modules. Sometimes, it is necessary to know whether the current browser supports a certain module, this is called "CSS module detection".

A generally applicable method is to determine whether a certain attribute value of the element's style object is a string.

typeof element.style.animationName === "string";
typeof element.style.transform === "string";

If the CSS property does exist, a string will be returned. Even if the property is not actually set, an empty string will be returned. If the property does not exist, it will return undefined.

document.body.style["maxWidth"]; // ""
document.body.style["maximumWidth"]; // undefined

The above code shows that this browser supports the max-width property, but does not support the maximum-width property.

Note that regardless of whether the CSS property name is written with or without conjunction lines, the style property can reflect the existence of the property.

document.body.style["backgroundColor"]; // ""
document.body.style["background-color"]; // ""

In addition, when using it, you need to take into account the CSS prefixes of different browsers.

var content = document.getElementById("content");
typeof content.style["webkitAnimation"] === "string";

This detection method can be written as a function.

function isPropertySupported(property) {
  if (property in document.body.style) return true;
  var prefixes = ["Moz", "Webkit", "O", "ms", "Khtml"];
  var prefProperty = property.charAt(0).toUpperCase() + property.substr(1);

  for (var i = 0; i < prefixes.length; i++) {
    if (prefixes[i] + prefProperty in document.body.style) return true;
  }

  return false;
}

isPropertySupported("background-clip");
// true

CSS Object

The browser natively provides CSS objects, and provides some tools and methods for JavaScript to manipulate CSS.

This object currently has two static methods.

CSS.escape()

The CSS.escape method is used to escape special characters in CSS selectors.

<div id="foo#bar"></div>

In the above code, the id attribute of the element contains a # sign, which has a special meaning in the CSS selector. It cannot be written directly as document.querySelector('#foo#bar'), it can only be written as document.querySelector('#foo\\#bar'). The reason why double slashes must be used here is that the single-quoted string itself escapes the slash once.

The CSS.escape method is used to escape those special characters.

document.querySelector("#" + CSS.escape("foo#bar"));

CSS.supports()

The CSS.supports method returns a boolean value indicating whether the current environment supports a certain CSS rule.

Its parameters can be written in two ways, one is that the first parameter is the property name, and the second is the property value; the other is that the entire parameter is a complete line of CSS statement.

// The first way of writing
CSS.supports("transform-origin", "5px"); // true

// The second way of writing
CSS.supports("display: table-cell"); // true

Note that the parameter of the second type of writing cannot have a semicolon at the end, otherwise the result will be inaccurate.

CSS.supports("display: table-cell;"); // false

window.getComputedStyle()

The inline style has the highest priority. Changing the inline style will usually be reflected immediately. However, the final style of web page elements is calculated based on various rules. Therefore, if you want to get the actual style of the element, it is not enough to only read the inline style. You need to get the style rules finally calculated by the browser.

The window.getComputedStyle method is used to return the final rule calculated by the browser. It accepts a node object as a parameter and returns a CSSStyleDeclaration instance, which contains the final style information of the specified node. The so-called "final style information" refers to the result of superposition of various CSS rules.

var div = document.querySelector("div");
var styleObj = window.getComputedStyle(div);
styleObj.backgroundColor;

In the above code, the background color obtained is the real background color of the div element.

Note that the CSSStyleDeclaration instance is a living object, and any changes to the style will be reflected in this instance in real time. In addition, this instance is read-only.

The getComputedStyle method can also accept a second parameter, which represents the pseudo-element of the current element (such as :before, :after, :first-line, :first-letter, etc.).

var result = window.getComputedStyle(div, ":before");

The following example is how to get the height of an element.

var elem = document.getElementById("elem-container");
var styleObj = window.getComputedStyle(elem, null);
var height = styleObj.height;
// Equivalent to
var height = styleObj["height"];
var height = styleObj.getPropertyValue("height");

The height property obtained by the above code is the height finally rendered by the browser, which is more reliable than the height obtained by other methods. Since styleObj is an instance of CSSStyleDeclaration, various instance properties and methods of CSSStyleDeclaration can be used.

There are a few things to note.

-CSS values ​​returned by CSSStyleDeclaration instances are all absolute units. For example, the length is in pixel units (the return value includes the px suffix), and the color is in the format of rgb(#, #, #) or rgba(#, #, #, #). -The short form of the CSS rule is invalid. For example, if you want to read the value of the margin property, you can't read it directly, you can only read the properties such as marginLeft, marginTop, etc.; for example, the font property cannot be read directly, only font-size Wait for a single attribute. -If you read the original CSS property name, you need to use square bracket operators, such as styleObj['z-index']; if you read the CSS property name in camel spelling, you can directly read styleObj.zIndex. -The cssText property of the CSSStyleDeclaration instance returned by this method is invalid and returns undefined.

CSS pseudo-elements

CSS pseudo-elements are elements added to the DOM through CSS, which are mainly generated by :before and :after selectors, and then use the content attribute to specify the content of the pseudo-element.

Below is a piece of HTML code.

<div id="test">Test content</div>

CSS to add pseudo-element :before is written as follows.

#test:before {
  content: "Before";
  color: #ff0;
}

The style object of the node element cannot read and write the style of the pseudo element. In this case, window.getComputedStyle() is used. To obtain pseudo-elements in JavaScript, you can use the following methods.

var test = document.querySelector("#test");

var result = window.getComputedStyle(test, ":before").content;
var color = window.getComputedStyle(test, ":before").color;

In addition, you can also use the getPropertyValue method of the CSSStyleDeclaration instance to get the properties of the pseudo-element.

var result = window
  .getComputedStyle(test, ":before")
  .getPropertyValue("content");
var color = window.getComputedStyle(test, ":before").getPropertyValue("color");

StyleSheet interface

Overview

The StyleSheet interface represents a style sheet of a web page, including the style sheet loaded by the <link> element and the style sheet embedded in the <style> element.

The styleSheets property of the document object can return all StyleSheet instances (that is, all style sheets) of the current page. It is an array-like object.

var sheets = document.styleSheets;
var sheet = document.styleSheets[0];
sheet instanceof StyleSheet; // true

If it is a style sheet embedded in a <style> element, there is another way to obtain an instance of StyleSheet, which is the sheet attribute of the node element.

// HTML code is <style id="myStyle"></style>
var myStyleSheet = document.getElementById("myStyle").sheet;
myStyleSheet instanceof StyleSheet; // true

Strictly speaking, the StyleSheet interface not only includes style sheets for web pages, but also style sheets for XML documents. Therefore, it has a subclass CSSStyleSheet that represents the CSS style sheet of the web page. The style sheet example we got in the web page is actually an example of CSSStyleSheet. This sub-interface inherits all the properties and methods of StyleSheet, and defines several of its own properties. The two interfaces are introduced together below.

Instance attributes

The StyleSheet instance has the following properties.

(1) StyleSheet.disabled

StyleSheet.disabled returns a boolean value indicating whether the style sheet is disabled. Manually setting the disabled attribute to true is equivalent to setting this style sheet to alternate stylesheet in the <link> element, that is, the style sheet will not take effect.

Note that the disabled attribute can only be set in JavaScript scripts, not in HTML statements.

(2) Stylesheet.href

Stylesheet.href returns the URL of the style sheet. For inline style sheets, this property returns null. This attribute is read-only.

document.styleSheets[0].href;

(3) StyleSheet.media

The StyleSheet.media property returns an array-like object (MediaList instance), and the member is a string representing the applicable medium. Indicates whether the current style sheet is used for screen (screen), print (print) or handheld device (handheld), or applicable to various media (all). This property is read-only and the default value is screen.

document.styleSheets[0].media.mediaText;
// "all"

The appendMedium method of the MediaList instance is used to add media; the deleteMedium method is used to delete media.

document.styleSheets[0].media.appendMedium("handheld");
document.styleSheets[0].media.deleteMedium("print");

(4) StyleSheet.title

The StyleSheet.title property returns the title property of the style sheet.

(5) StyleSheet.type

The StyleSheet.type property returns the type property of the style sheet, which is usually text/css.

document.styleSheets[0].type; // "text/css"

(6) StyleSheet.parentStyleSheet

The @import command of CSS allows other style sheets to be loaded in the style sheet. The StyleSheet.parentStyleSheet property returns the style sheet that contains the current style sheet. If the current style sheet is the top-level style sheet, this property returns null.

if (stylesheet.parentStyleSheet) {
  sheet = stylesheet.parentStyleSheet;
} else {
  sheet = stylesheet;
}

(7) StyleSheet.ownerNode

The StyleSheet.ownerNode property returns the DOM node where the StyleSheet object is located, usually <link> or <style>. For those style sheets referenced by other style sheets, this attribute is null.

// HTML code is
// <link rel="StyleSheet" href="example.css" type="text/css" />
document.styleSheets[0].ownerNode; // [object HTMLLinkElement]

(8) CSSStyleSheet.cssRules

The CSSStyleSheet.cssRules property points to an array-like object (CSSRuleList instance), and each member in it is a CSS rule of the current style sheet. Use the cssText property of this rule to get the string corresponding to the CSS rule.

var sheet = document.querySelector("#styleElement").sheet;

sheet.cssRules[0].cssText;
// "body {background-color: red; margin: 20px; }"

sheet.cssRules[1].cssText;
// "p {line-height: 1.4em; color: blue; }"

Each CSS rule also has a style attribute, which points to an object for reading and writing specific CSS commands.

cssStyleSheet.cssRules[0].style.color = "red";
cssStyleSheet.cssRules[1].style.color = "purple";

(9) CSSStyleSheet.ownerRule

Some style sheets are imported through the @import rule, and its ownerRule property will return a CSSRule instance, which represents the line of the @import rule. If the current style sheet is not imported through @import, the ownerRule property returns null.

Example method

(1) CSSStyleSheet.insertRule()

The CSSStyleSheet.insertRule method is used to insert a new CSS rule in the current style sheet.

var sheet = document.querySelector("#styleElement").sheet;
sheet.insertRule("#block {color: white }", 0);
sheet.insertRule("p {color: red }", 1);

This method can accept two parameters. The first parameter is a string representing a CSS rule. There can only be one rule, otherwise an error will be reported. The second parameter is the insertion position of the rule in the style sheet (starting from 0). This parameter is optional and defaults to 0 (that is, inserted at the head of the style sheet by default). Note that if the insertion position is greater than the number of existing rules, an error will be reported.

The return value of this method is the position number of the newly inserted rule.

Note that browsers have many [limitations] for scripts to insert rules into style sheets (https://drafts.csswg.org/cssom/#insert-a-css-rule). Therefore, this method is best used in try...catch.

(2) CSSStyleSheet.deleteRule()

The CSSStyleSheet.deleteRule method is used to remove a rule in the style sheet, and its parameter is the position of the rule in the cssRules object. This method has no return value.

document.styleSheets[0].deleteRule(1);

Example: Add a style sheet

There are two ways to add a style sheet to a web page. One is to add a built-in style sheet, that is, add a <style> node to the document.

// Writing method one
var style = document.createElement("style");
style.setAttribute("media", "screen");
style.innerHTML = "body{color:red}";
document.head.appendChild(style);

// Writing method two
var style = (function () {
  var style = document.createElement("style");
  document.head.appendChild(style);
  return style;
})();
style.sheet.insertRule(".foo{color:red;}", 0);

The other is to add an external style sheet, that is, add a <link> node to the document, and then point the href attribute to the URL of the external style sheet.

var linkElm = document.createElement("link");
linkElm.setAttribute("rel", "stylesheet");
linkElm.setAttribute("type", "text/css");
linkElm.setAttribute("href", "reset-min.css");

document.head.appendChild(linkElm);

CSSRuleList interface

The CSSRuleList interface is an array-like object, representing a set of CSS rules, and the members are all CSSRule instances.

Get the CSSRuleList instance, usually through the StyleSheet.cssRules property.

// HTML code is as follows
// <style id="myStyle">
// h1 {color: red;}
// p {color: blue;}
// </style>
var myStyleSheet = document.getElementById("myStyle").sheet;
var crl = myStyleSheet.cssRules;
crl instanceof CSSRuleList; // true

In the CSSRuleList instance, each rule (CSSRule instance) can be obtained through rules.item(index) or rules[index]. The number of CSS rules can be obtained through rules.length. Still use the above example.

crl[0] instanceof CSSRule; // true
crl.length; // 2

Note that adding rules and deleting rules cannot be operated on the CSSRuleList instance, but on the instance of its parent element StyleSheet, through StyleSheet.insertRule() and StyleSheet.deleteRule().

CSSRule interface

Overview

A CSS rule consists of two parts: CSS selector and style declaration. The following is a typical CSS rule.

.myClass {
  color: red;
  background-color: yellow;
}

JavaScript manipulates CSS rules through the CSSRule interface. The CSSRule instance is generally obtained through the CSSRuleList interface (StyleSheet.cssRules).

// HTML code is as follows
// <style id="myStyle">
// .myClass {
// color: red;
// background-color: yellow;
//}
// </style>
var myStyleSheet = document.getElementById("myStyle").sheet;
var ruleList = myStyleSheet.cssRules;
var rule = ruleList[0];
rule instanceof CSSRule; // true

CSSRule instance properties

(1) CSSRule.cssText

The CSSRule.cssText property returns the text of the current rule, or use the above example.

rule.cssText;
// ".myClass {color: red; background-color: yellow; }"

If the rule is to load (@import) other style sheets, the cssText property returns @import'url'.

(2) CSSRule.parentStyleSheet

The CSSRule.parentStyleSheet property returns the style sheet object (StyleSheet instance) where the current rule is located, or use the above example.

rule.parentStyleSheet === myStyleSheet; // true

(3) CSSRule.parentRule

The CSSRule.parentRule property returns the parent rule that contains the current rule. If there is no parent rule (that is, the current rule is the top-level rule), it returns null.

The most common case of the parent rule is that the current rule is contained in the @media rule code block.

// HTML code is as follows
// <style id="myStyle">
// @supports (display: flex) {
// @media screen and (min-width: 900px) {
// article {
// display: flex;
//}
//}
//}
// </style>
var myStyleSheet = document.getElementById("myStyle").sheet;
var ruleList = myStyleSheet.cssRules;

var rule0 = ruleList[0];
rule0.cssText;
// "@supports (display: flex) {
// @media screen and (min-width: 900px) {
// article {display: flex;}
//}
// }"

// Since this rule is embedded with other rules,
// So it has a cssRules property, and this property is an instance of CSSRuleList
rule0.cssRules instanceof CSSRuleList; // true

var rule1 = rule0.cssRules[0];
rule1.cssText;
// "@media screen and (min-width: 900px) {
// article {display: flex;}
// }"

var rule2 = rule1.cssRules[0];
rule2.cssText;
// "article {display: flex; }"

rule1.parentRule === rule0; // true
rule2.parentRule === rule1; // true

(4) CSSRule.type

The CSSRule.type property returns an integer value indicating the type of the current rule.

The most common types are as follows.

-1: Common style rules (CSSStyleRule instance) -3: @import rule -4: @media rule (CSSMediaRule instance) -5: @font-face rule

CSSStyleRule interface

If a CSS rule is a normal style rule (without special CSS commands), then in addition to the CSSRule interface, it also deploys the CSSStyleRule interface.

The CSSStyleRule interface has the following two properties.

(1) CSSStyleRule.selectorText

The CSSStyleRule.selectorText property returns the selector of the current rule.

var stylesheet = document.styleSheets[0];
stylesheet.cssRules[0].selectorText; // ".myClass"

Note that this attribute is writable.

(2) CSSStyleRule.style

The CSSStyleRule.style property returns an object (CSSStyleDeclaration instance), which represents the style declaration of the current rule, that is, the part inside the braces after the selector.

// HTML code is
// <style id="myStyle">
// p {color: red;}
// </style>
var styleSheet = document.getElementById("myStyle").sheet;
styleSheet.cssRules[0].style instanceof CSSStyleDeclaration;
// true

The cssText property of the CSSStyleDeclaration instance can return all style declarations in a string format.

styleSheet.cssRules[0].style.cssText;
// "color: red;"
styleSheet.cssRules[0].selectorText;
// "p"

CSSMediaRule interface

If a CSS rule is a @media code block, then in addition to the CSSRule interface, it also deploys the CSSMediaRule interface.

This interface mainly provides media property and conditionText property. The former returns an object (MediaList instance) representing the @media rule, and the latter returns the effective conditions of the @media rule.

// HTML code is as follows
// <style id="myStyle">
// @media screen and (min-width: 900px) {
// article {display: flex;}
//}
// </style>
var styleSheet = document.getElementById("myStyle").sheet;
styleSheet.cssRules[0] instanceof CSSMediaRule;
// true

styleSheet.cssRules[0].media;
// {
// 0: "screen and (min-width: 900px)",
// appendMedium: function,
// deleteMedium: function,
// item: function,
// length: 1,
// mediaText: "screen and (min-width: 900px)"
//}

styleSheet.cssRules[0].conditionText;
// "screen and (min-width: 900px)"

window.matchMedia()

Basic usage

The window.matchMedia method is used to convert the conditional statement of CSS MediaQuery into a MediaQueryList instance.

var mdl = window.matchMedia("(min-width: 400px)");
mdl instanceof MediaQueryList; // true

In the above code, the variable mdl is an instance of mediaQueryList.

Note that if the parameter is not a valid MediaQuery conditional statement, window.matchMedia will not report an error and still return a MediaQueryList instance.

window.matchMedia("bad string") instanceof MediaQueryList; // true

Instance properties of the MediaQueryList interface

The MediaQueryList instance has three properties.

(1) MediaQueryList.media

The MediaQueryList.media property returns a string representing the corresponding MediaQuery conditional statement.

var mql = window.matchMedia("(min-width: 400px)");
mql.media; // "(min-width: 400px)"

(2) MediaQueryList.matches

The MediaQueryList.matches property returns a Boolean value, indicating whether the current page meets the specified MediaQuery conditional statement.

if (window.matchMedia("(min-width: 400px)").matches) {
  /* The current viewport is not less than 400 pixels*/
} else {
  /* The current viewport is less than 400 pixels*/
}

The following example loads the corresponding CSS style sheet according to whether the mediaQuery matches the current environment.

var result = window.matchMedia("(max-width: 700px)");

if (result.matches) {
  var linkElm = document.createElement("link");
  linkElm.setAttribute("rel", "stylesheet");
  linkElm.setAttribute("type", "text/css");
  linkElm.setAttribute("href", "small.css");

  document.head.appendChild(linkElm);
}

(3) MediaQueryList.onchange

If the adaptation environment of the MediaQuery conditional statement changes, the change event will be triggered. The MediaQueryList.onchange property is used to specify the listener function for the change event. The parameter of this function is the change event object (MediaQueryListEvent instance), which is similar to the MediaQueryList instance and also has the media and matches attributes.

var mql = window.matchMedia("(max-width: 600px)");

mql.onchange = function (e) {
  if (e.matches) {
    /* The viewport does not exceed 600 pixels*/
  } else {
    /* The viewport exceeds 600 pixels*/
  }
};

In the above code, there are two possibilities after the change event occurs. One is that the display width changes from more than 600 pixels to less than, and the other is from less than 600 pixels to more than, so it is necessary to determine which situation is currently in the monitoring function.

Instance methods of the MediaQueryList interface

The MediaQueryList instance has two methods MediaQueryList.addListener() and MediaQueryList.removeListener(), which are used to add or remove listener functions for the change event.

var mql = window.matchMedia("(max-width: 600px)");

// Specify the monitoring function
mql.addListener(mqCallback);

// Cancel the monitoring function
mql.removeListener(mqCallback);

function mqCallback(e) {
  if (e.matches) {
    /* The viewport does not exceed 600 pixels*/
  } else {
    /* The viewport exceeds 600 pixels*/
  }
}

Note that the MediaQueryList.removeListener() method cannot cancel the listener function specified by the MediaQueryList.onchange property.