This is the first day of my participation in the August More Text challenge

preface

Today I encountered a problem when working with a CSS style in the project: how to get CSS custom properties using JS. For a moment I couldn’t remember how to get the property using JS.

We know that CSS custom attributes are written in a special way, starting with two minus signs (–my-name: red;) And how do you access it? Direct style access?? GetComputedStyle?? — How to name the hump of my name?

With these questions began to look up information, and then write this article to summarize.

Look at a simple example:

<html>
<head>
    <meta charset="utf-8">
    <style>
        :root{
            --my-val: red;
            --in-val: 10px;
        }
        #ele{
            background-color: var(--my-va);
            font-weight: 500;
            border: 1px solid #ccc;
            width: 300px;
            float: right;
            
        }
    </style>
    <link href="test.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div id="ele" 
    style="--height-val:200px; height:var(--height-val); border-radius:var(--in-val); text-align: center;">Test to get CSS properties</div>
</body>
</html>
Copy the code

External file: test.css

#ele {
    color: blue;
}
Copy the code

Style object

A common way to set and access style properties is directly through the Style object, which returns a CSSStyleDeclaration object.

Look at the following code:

window.onload= function() {
    let ele = document.getElementById('ele');

    // Use style access directly, requiring the camel name
    console.log(ele.style.height);    //var(--height-val)
    console.log(ele.style.borderRadius);   //var(--in-val)
    console.log(ele.style['text-align']);      //center
    console.log(ele.style.backgroundColor);  // Can't get tag style
    console.log(ele.style.color);   // Cannot get external file styles
    console.log(ele.style.cssText);
    console.log(ele.style['--height-val']);  // Cannot get custom attributes
    
    // Set properties with style
    ele.style.width = '200px';
    ele.style['line-height'] = '200px';
Copy the code

The result is as follows:

  • Style objects can only get inline styles (the style property).

  • If the CSS property has a hyphen, you need to use a camel name or brackets to access it.

  • The float property (JavaScript reserved word) is special. Google can write float directly, but Internet Explorer and Firefox do not. Internet Explorer requires styleFloat, and non-Internet Explorer can use cssFloat

  • The Style object has a cssText property that gets all the style properties set inside the line.

  • Style objects do not have direct access to custom properties.

  • If the value of the style attribute is obtained by the var function, the style object returns the var function intact and does not evaluate it itself.

  • You can set CSS property values directly through the Style object.

getComputedStyle

Another common method is getComputedStyle, which returns a CSSStyleDeclaration object.

Grammar:

let style = window.getComputedStyle(element, [pseudoElt]);
Copy the code

Parameters:

  • Element: Mandatory, element to get style.
  • PseudoElt: Optional, string of pseudoelements. Normal elements must be omitted or set to NULL

Look at accessing style attributes with getComputedStyle:

window.onload= function() {
    let ele = document.getElementById('ele');
    let computedValue = getComputedStyle(ele) || document.defaultView.getComputedStyle(ele);
    
    console.log(computedValue.width);   // access internal styles at 300px
    console.log(computedValue.borderRadius);  //10px inline style
    console.log(computedValue['text-align']);  //center  
    console.log(computedValue.color);   // rgb(0, 0, 255)
    console.log(computedValue.backgroundColor);  // RGB (255, 0, 0) returns the result of the var function
    console.log(computedValue['--height-val']);  //undefined cannot access custom attributes
    console.log(computedValue.cssFloat);  //right 
    
    // Only read but not write
    computedValue.width = '200px';
}
Copy the code

The result is as follows:

  • GetComputedStyle only supports reading styles and does not support rewriting.

  • GetComputedStyle captures the style of the browser’s final rendering, including inline style (inline), internal style (style tag), and external style (link tag).

  • As with style objects, hyphenated properties need to be named with a hump or brackets.

  • If the attribute value is set to var, getComputedStyle returns the result of the var function directly.

  • Generally getComputedStyle can call through a window object directly, but on the firefox3.6 when accessing a child within the framework of the style, the document must be used. The defaultView. GetComputedStyle

  • IE9 does not support getCoumputedStyle below, and uses the currentStyle object to read the final display style of the element.

getAttribute/setAttribute

GetAttribute is a special method that returns the attribute value specified by the element, or null or an empty string “” if none exists.

What does CSS style have to do with accessing an element’s attribute value? Although you cannot access a specific style attribute, you can access the element’s style attribute (inline style), which returns a string if the style attribute is set to the element, and null otherwise

The getAttribute/setAttribute is a better method of compatibility, IE’s support is also very good.

let ele = document.getElementById('ele');

// Get the element's style attribute
console.log(ele.getAttribute('style'));

// Set the style directly
ele.setAttribute('style'.'width: 200px; --hg: 100px; height:var(--hg); ');
Copy the code

The result is as follows:

  • The getAttribute/setAttribute mainly through attribute names for elements of the element nodes of attribute values, so you can use this method can obtain the element node style attribute values. However, this method is not generally used to get and set style properties.
  • The value of the style attribute obtained by getAttribute matches the cssText of the style object

getPropertyValue

GetPropertyValue can also be used to request the value of a CSS property, but it is not directly accessible through the element node, but as a method of the CSSStyleDeclaration object. So using getPropertyValue needs to work with either a Style object or a getComputedStyle method.

let ele = document.getElementById('ele');

// Get the CSSStyleDeclaration object with style
let eleStyle = ele.style;
console.log(eleStyle.getPropertyValue('text-align'));   //center
console.log(eleStyle.getPropertyValue('height'));       //var(--height-val)
console.log(eleStyle.getPropertyValue('--height-val'));  //200px


// Get the CSSStyleDeclaration object with getComputedStyle
let computedValue = getComputedStyle(ele) || document.defaultView.getComputedStyle(ele);
console.log(computedValue.getPropertyValue('background-color'));  //rgb(255, 0, 0)
console.log(computedValue.getPropertyValue('color'));   //rgb(0, 0, 255)
console.log(computedValue.getPropertyValue('float'));   //right
console.log(computedValue.getPropertyValue('--in-val'));   //10px


// Get the CSSStyleDeclaration from the cssRules style object
let eleDec = document.styleSheets[1].cssRules[0].style;
console.log(eleDec.getPropertyValue('color'));   //blue
Copy the code

Execution Result:

  • To use the getPropertyValue method, you first need to get the CSSStyleDeclaration object.

  • The getPropertyValue method accesses properties directly without modifying property names (including hyphenates and floats), camel naming, and other conversions to element properties.

  • The getPropertyValue method can access custom properties.

stylesheets

You can get CSS stylesheets through Document. stylesheets. Each CSS stylesheet has a cssRules property (read only) that returns a CSSRuleList.

There are several common ways to add CSSStyleSheet:

  • Use the @import import style
let sheets = document.styleSheets;
for(let i=0; i<sheets.length; i++) {
    console.log(sheets);
    let ruleList = sheets[i].cssRules;
    for(let j=0; j<ruleList.length; j++) {
        console.log(ruleList[j]);
        console.log(ruleList[j].style); }}Copy the code

The result is as follows:

We can also use insertRule to add style rules, stylesheet. InsertRule (rule, [, index]); AddRule (Selector,rule,[,index]) is not supported in browsers below Internet Explorer 9. The addRule method is used: addRule(Selector,rule,[,index]).

conclusion

CSS style attributes method has a lot of kinds, but CSSStyleDeclaration. GetPropertyValue compatibility is a kind of good writing, it does not need to convert the attribute name, also can have direct access to custom properties.

Finally, find sometimes Settings! Important seems to fail, see online recommend using setProperty, writing: element. The style.css. SetProperty (propertyName, value, priority);

Refer to the article

JS Several ways to set CSS styles

CSSStyleSheet