CSS details of the JavaScript core (CSS rules, getComputedStyle(), matchMedia(), CSS events)

tags: JavaScript advanced core

table of Contents

1 CSS rules

1.1 CSSRule interface

1.1.1 cssText

1.1.2 parentStyleSheet

1.1.3 parentRule

1.1.4 type

1.2 CSSStyleRule interface

1.2.1 selectorText property

1.2.2 style attribute

1.3 CSSMediaRule interface

1.4 CSSStyleDeclaration object

1.4.1 getPropertyPriority()

1.4.2 getPropertyValue()

1.4.3 item()

1.4.4 removeProperty()

1.4.5 setProperty()

2 window.getComputedStyle()

3 window.matchMedia()

3.1 Basic usage

3.2 Listening events

4 CSS events

4.1 transitionEnd event

4.2 animationstart event, animationend event, animationiteration event


1 CSS rules

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

Selector {property: attribute value}

.myClass {
  background-color: yellow;
}

1.1 CSSRule interface

The CSS rules deploy the CSSRule interface, which includes the following properties.

1.1.1 cssText

The cssText property returns the text of the current rule.

// CSS code is
// body { background-color: darkblue; }

var stylesheet = document.styleSheets[0];
stylesheet.cssRules[0].cssText
// body { background-color: darkblue; }

1.1.2 parentStyleSheet

The parentStyleSheet property returns a stylesheet object that defines the current rule.

1.1.3 parentRule

parentRule returns the CSS rule containing the current rule. The most typical case is that the current rule is contained in a @media code block. If the current rule is a top-level rule, the property returns null.

1.1.4 type

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

The most common types are the following.

  • 1: style rules, deployed CSSStyleRule interface
  • 3: Input rules, deployed CSSImportRule interface
  • 4: Media rules, deployed CSSMediaRule interface
  • 5: Font rules, deployed CSSFontFaceRule interface

1.2 CSSStyleRule interface

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

The CSSRule interface has the following two properties.

1.2.1 selectorText property

The selectorText property returns the selector for the current rule.

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

1.2.2 style attribute

The style attribute returns an object that represents the style declaration for the current rule, which is the part inside the braces after the selector.This object deploys the CSSStyleDeclaration interface, which uses its cssText property to return all style declarations in the form of strings.

document.styleSheets[0].cssRules[0].style.cssText
// "background-color: gray;font-size: 120%;"

1.3 CSSMediaRule interface

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

This interface mainly provides a media attribute that can return the media rules of the @media code block.

1.4 CSSStyleDeclaration object

The style declaration part of each CSS rule (the inner part of the braces) is aCSSStyleDeclarationObjects mainly include three cases.

  • Inline style of HTML elements (<elem style="...">)
  • The style attribute of the CSSStyleRule interface
  • Return result of window.getComputedStyle()

Each CSS property is a property of the CSSStyleDeclaration object. However, even the lexicon needs to be programmed with camel spelling.

var styleObj = document.styleSheets[0].cssRules[1].style;
styleObj.color // "red";
styleObj.fontSize // "100%"

In addition to CSS properties, the CSSStyleDeclaration object also includes the following properties.

  • cssText: All style declaration text for the current rule. This property is readable and writable and can be used to set the current rule.
  • Length: How many declarations the current rule contains.
  • parentRule: The rule containing the current rule, the parentRule attribute of the CSSRule interface.

The CSSStyleDeclaration object includes the following methods.

1.4.1 getPropertyPriority()

The getPropertyPriority method returns the priority of the specified declaration, if any, is "important", otherwise it is an empty string.

var styleObj = document.styleSheets[0].cssRules[1].style;
styleObj.getPropertyPriority('color') // ""

1.4.2 getPropertyValue()

The getPropertyValue method returns the value of the specified declaration.

// CSS code is
// color:red;

var styleObj = document.styleSheets[0].cssRules[1].style;
styleObj.getPropertyValue('color') // "red"

1.4.3 item()

The item method returns the name of the property at the specified location.

var styleObj = document.styleSheets[0].cssRules[1].style;
styleObj.item(0) // "color"
 // or
styleObj[0] // "color"

1.4.4 removeProperty()

The removeProperty method is used to delete a CSS property and return the deleted value.

// CSS code is
// color:red;

var styleObj = document.styleSheets[0].cssRules[1].style;
styleObj.removeProperty('color') // "red"

1.4.5 setProperty()

The setProperty method is used to set the specified CSS property with no return value.

var styleObj = document.styleSheets[0].cssRules[1].style;
styleObj.setProperty('color', 'green', 'important');

Below is an example of traversing all the properties of a CSS rule.

var styleObj = document.styleSheets[0].cssRules[0].style;
for (var i = styleObj.length - 1; i >= 0; i--) {
   var nameString = styleObj[i];
   styleObj.removeProperty(nameString);
}

It's easier to remove all the properties of a CSS rule. The easier way is to set the cssText property to an empty string.

styleObj.cssText = '';

2 window.getComputedStyle()

The getComputedStyle method accepts a DOM node object as a parameterReturns an object containing the final style information for the node. The so-called "final style information" refers to the result of superimposition of various CSS rules.

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

The getComputedStyle method can also accept a second parameter representing the pseudo-element of the specified node.

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

The getComputedStyle method returns a CSSStyleDeclaration object. But at this time, this object is read-only, that is, it can only be used to read style information, and can not be used for setting. If you want to set the style, you should use the style attribute of the Element node.

var elem = document.getElementById("elem-container");
var hValue = window.getComputedStyle(elem,null).getPropertyValue("height");

3 window.matchMedia()

3.1 Basic usage

The window.matchMedia method is used to check the CSS mediaQuery statement.This method is supported by the latest versions of various browsers (including IE 10+). For older browsers that do not support this method, a third-party library, matchMedia.js, can be used.

CSS's mediaQuery statement is a bit like an if statement. As long as the display medium (including the browser and screen) meets the conditions set by the mediaQuery statement, the statement inside the block is executed. The following is an example of a mediaQuery statement.

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

The above CSS code indicates that the block is valid for all media, and the maximum width of the viewport must not exceed 700 pixels. If the condition is met, the background of the body element is set to #FF0.

It should be noted that mediaQuery accepts two width/height metrics, one is the width/height of the "viewport" in the above example, and the other is the width/height of the "device". Below is an example.

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

The width/height of the viewport is measured using documentElement.clientWidth/clientHeight, in CSS pixels; the width/height of the device (device-width/device-height) is measured using screen.width/height. The pixels of the device hardware.

The window.matchMedia method takes a string of a mediaQuery statement as a parameter and returns amediaQueryList object. This object has the following two properties.

  • Media: Returns the string of the mediaQuery statement being queried.
  • Matches: Returns a Boolean value indicating whether the current environment matches the query statement.
var result = window.matchMedia("(min-width: 600px)");
result.media // (min-width: 600px)
result.matches // true

Here's another example of executing different JavaScript code depending on whether mediaQuery matches the current environment.

var result = window.matchMedia('@media all and (max-width: 700px)');

if (result.matches) {
     Console.log ('page width is less than or equal to 700px');
} else {
     Console.log ('page width is greater than 700px');
}

The following example loads the corresponding CSS stylesheet based on whether 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.2 Listening events

window.matchMediaMethod returnedThe MediaQueryList object has two methodsUsed to listen for events:addListener method and removeListener method. If the result of the mediaQuery query changes, the specified callback function is called.

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

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

 // Undo the callback function
mql.removeListener(mqCallback);

function mqCallback(mql) {
  if (mql.matches) {
         // width less than or equal to 700 pixels
  } else {
         // width is greater than 700 pixels
  }
}

In the above code, the parameter of the callback function is the MediaQueryList object. There are two possible cases for calls to callback functions. One is that the display width is changed from 700 pixels or more to the other, and the other is from 700 pixels or less to the above, so the current screen width is judged inside the callback function.

4 CSS events

4.1 transitionEnd event

After the transition of the CSS ends, the transitionEnd event is triggered.

el.addEventListener("transitionend", onTransitionEnd, false);

function onTransitionEnd() {
  console.log('Transition end');
}

The event object of transitionEnd has the following properties.

  • propertyName: The name of the CSS property in which the transition effect occurs.
  • elapsedTime:The number of seconds that the transition effect lasts, without the transition-delay time.
  • pseudoElement: If the transition effect occurs in a pseudo-element, the name of the pseudo-element is returned, starting with "::". Returns an empty string if it does not occur on a pseudo-element.

When you actually use the transitionend event, you need to add a browser prefix.

el.addEventListener('webkitTransitionEnd '
  + 'transitionend '
  + 'msTransitionEnd '
  + 'oTransitionEnd ', function(){
  el.style.transition = 'none';
});

4.2 animationstart event, animationend event, animationiteration event

CSS animations have the following three events.

  • Animationstart event: Triggered when the animation starts.
  • Animationend event: Triggered when the animation ends.
  • Animationiteration event: start a new roundAnimation loopTriggered when. If the animation-iteration-count attribute is equal to 1, the event is not triggered, ie only one round of CSS animation is played, and the animationiteration event is not triggered.
div.addEventListener('animationiteration', function() {
     Console.log('Complete an animation');
});

The event objects of these three events have the animationName property (returning the CSS property name that produces the transition effect) and the elapsedTime property (the number of seconds the animation has been run). For the animationstart event, the elapsedTime attribute is equal to 0 unless the animation-delay attribute is equal to a negative value.


var el = document.getElementById("animation");

el.addEventListener("animationstart", listener, false);
el.addEventListener("animationend", listener, false);
el.addEventListener("animationiteration", listener, false);

function listener(e) {
  var li = document.createElement("li");
  switch(e.type) {
    case "animationstart":
      li.innerHTML = "Started: elapsed time is " + e.elapsedTime;
      break;
    case "animationend":
      li.innerHTML = "Ended: elapsed time is " + e.elapsedTime;
      break;
    case "animationiteration":
      li.innerHTML = "New loop started at time " + e.elapsedTime;
      break;
  }
  document.getElementById("output").appendChild(li);
}

The result of the above code is as follows.

Started: elapsed time is 0
New loop started at time 3.01200008392334
New loop started at time 6.00600004196167
Ended: elapsed time is 9.234000205993652

The animation-play-state property controls the state of the animation (pause/play), which is added to the browser prefix.

element.style.webkitAnimationPlayState = "paused";
element.style.webkitAnimationPlayState = "running";

Intelligent Recommendation

getComputedStyle and currentStyle get the elements of the current style css

CSS styles are divided into three categories: Inline style: It is written on the label inside, inline styles only valid for the label where Internal Style: It is written in theHTMLInside, the interior...

JS gets CSS style (style/getComputedStyle/currentStyle)

CSS styles are divided into three categories: Inline style:It is written in the tag, and the embedded style is only valid for all tags. A Internal style:It is written in HTML, and the internal style i...

Get the element CSS value getComputedStyle, currentStyle, style

1.getComputedStyle Through getComputedStyle, you can get all the final CSS property values ​​of the current element. The returned style is a real-time CSSStyleDeclaration object. When the style of the...

Familiar with the getComputedStyle method of obtaining the CSS value of an element

Why can't 80% of programmers be architects? >>>   1. Sui Sui Nian ~ Preface      We have all used jQuery's CSS() method, and its underlying operation uses the ge...

Css details

1. Most browsers place the list at 30 pixels from the left border of the unordered list (default padding). The unordered list itself is about 10 pixels from the top border of the container (the defaul...

More Recommendation

CSS Core

A: font class properties II: Class attribute list Three: Background Properties Four: the float property...

Browser events and element css operations in JavaScript

Browser events and element css operations in JavaScript Common DOM events: Mouse event Form event: Keyboard events: Element CSS operations Change element style method external style, internal style, i...

CSS learning CSS cascading rules

table of Contents css stack css stack This is for the conflicts of declarations in multiple rules. If they are all different types of declarations, they can be applied directly without comparison and ...

CSS Grammar and Rules-Relearn CSS

I'mThree diamonds, One in"Technology Galaxy"Waiting for you to come together for lifelong learning. Like is power, attention is recognition, comment is caring! See you next time ! Preface To...

CSS - CSS and JavaScript combination of

Foreword CSS and JavaScript combination is very tight, so in this respect we need to learn good, then I will use an example to introduce how to use CSS and JavaScript combination. content Pictures fad...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top