The scripting operation of jacascript CSS style

Foreword: This is the author's own understanding and arrangement after learning. If there are any mistakes or doubts, please correct them and I will keep updating them.

There are three ways to introduce CSS: interline style, internal style and external style.

In practice, when we use javascript to manipulate CSS styles:

  1. When we change a few styles of elements, we usually change their inter-line styles directly.
  2. cssText can be used to change the variety of elements.
  3. More commonly, css classes are used to set the style before and after changes to classes in advance. Just change its class name className, obj.className;
  4. If you want to change more than one class name, it is more convenient to use classList, which is not supported by IE9 and browsers below.

Interline Style

Inter-line style is also called inline style. Element element nodes provide style attributes to manipulate CSS inter-line style.

If a CSS attribute name contains one or more hyphens, the format of the attribute name should be to remove the hyphens and capitalize the letters immediately after each hyphen (hump nomenclature);

        <div class="wrapper" style="width: 500px;height: 200px;border-bottom: 10px solid #ff0;"></div>
        <script type="text/javascript">
            var oWrapper = document.getElementsByClassName('wrapper')[0];
            console.log(oWrapper.style.borderBottom);//10px solid rgb(255, 255, 0)
        </script>

In fact, if you manipulate the inter-line style, you can manipulate style attributes by using the attributes operation methods of element nodes, such as hasAttribute(), getAttribute(), setAttribute(), removeAttribute(), etc.

        <div class="wrapper" style="width: 500px;height: 200px;border-bottom: 10px solid #ff0;"></div>
        <script type="text/javascript">
            var oWrapper = document.getElementsByClassName('wrapper')[0];
            oWrapper.setAttribute('style','background-color: #0ff;')
            //setAttribute Setting the whole of the current properties
            console.log(oWrapper.hasAttribute('style'));//true
            console.log(oWrapper.getAttribute('style'));//background-color: #0ff;
        </script>

 

cssText

CSS code (interline style) in style attributes can be accessed through cssText attributes.

In read mode, cssText returns the browser's internal representation of CSS code in style attributes; IE8-browser returns attribute names in full uppercase

In write mode, the value assigned to cssText overrides the value of the entire style attribute.

        <div class="wrapper" style="width: 500px;height: 200px;border-bottom: 10px solid #ff0;"></div>
        <script type="text/javascript">
            var oWrapper = document.getElementsByClassName('wrapper')[0];
            console.log(oWrapper.style.cssText);
            //width: 500px; height: 200px; border-bottom: 10px solid rgb(255, 255, 0);
            
            oWrapper.style.cssText = 'background-color: #0ff;';
            console.log(oWrapper.style.cssText);//background-color: rgb(0, 255, 255);
        </script>

 

length

The length attribute returns the number of styles in the inline style; browsers IE8 and below do not support it;

        <div class="wrapper" style="width: 500px;height: 200px;border-bottom: 10px solid #ff0;"></div>
        <script type="text/javascript">
            var oWrapper = document.getElementsByClassName('wrapper')[0];
            console.log(oWrapper.style.length);//5
            //width height border-bottom-width border-bottom-style border-bottom-color
        </script>

 

Method

GetProperty Priority (propertyName) returns "important" if the given property uses the! Important setting; otherwise returns an empty string; browsers IE8 and below do not support it

The setProperty(propertyName,value,priority) method sets the given attribute to the corresponding value, and adds a priority flag ("important" or an empty string), which has no return value; browsers IE8 and below do not support it.

The removeProperty(propertyName) method deletes a given attribute from the style and returns the attribute value of the deleted attribute; browsers IE8 and below do not support it

        <div id="test" style="height: 40px!important;width: 40px;background-color: pink;border:10px solid #f0f"></div>
        <script>
            var oTest = document.getElementById('test');
            
            //getPropertyPriority() If a given attribute is used!important Settings, then returns"important";Otherwise, an empty string is returned.
            console.log(oTest.style.getPropertyPriority('height'));//'important'
            console.log(oTest.style.getPropertyPriority('width'));//''
            
            //setProperty(propertyName,value,priority)Method Sets the given attribute to its corresponding value and adds a priority flag("important"Or an empty string)
            oTest.style.setProperty('width','100px');
            console.log(oTest.style.width);//100px
            console.log(oTest.style.getPropertyPriority('width'));//''
            
            oTest.style.setProperty('background-color','blue','important');
            console.log(oTest.style.backgroundColor);//blue
            console.log(oTest.style.getPropertyPriority('background-color'));//important
            
            //removeProperty()Method deletes a given attribute from the style and returns the attribute value of the deleted attribute
            console.log(oTest.style.border);//10px solid rgb(255, 0, 255)
            oTest.style.removeProperty('border');
            console.log(oTest.style.border);//''
        </script>

 

Computing Style

The rendering result of elements is the final result of multiple CSS style games, which is also the meaning of C(cascade) cascade in CSS. cssText can only get the interline style, which is usually not the result we want. Sometimes we need the element's computing style.

The computed Style of an element is a set of attributes that are actually used when displaying elements, and it is also represented by a CSSStyleDeclaration object. However, the actual style is read-only, which is mainly realized by getComputedStyle() method. IE8 and browsers below do not support it.

The getComputedStyle() method takes two parameters: the element of the calculation style and a pseudo-element string. If no pseudo-element information is required, the second parameter can be null. The getComputedStyle() method returns a CSSStyleDeclaration object containing all the computational styles of the current element;

The second parameter represents the pseudo-element string, including ": before", "after", "first-line" and so on. If set to null or omit not to write, the CSSStyleDeclaration object of its own element is returned.

For font, background, border and other composite styles, browsers handle them differently. chrome returns the entire composite style, while IE9+, firefox and safari output empty strings';

In the calculation style, relative units such as percentages are converted to absolute values.

        <style type="text/css">
            #test{
                background-color: #ff0;
            }
            #test:before{
                content: "";
                width: 50px;
                display: block;
            }
        </style>
        <div id="test" style="width: 100px;height: 200px;"></div>
        <script type="text/javascript">
            var oTest = document.getElementById('test');
            
            console.log(getComputedStyle(oTest).width);//100px
            console.log(getComputedStyle(oTest).height);//200px
            
            console.log(getComputedStyle(oTest).backgroundColor);//rgb(255, 255, 0)
            
            console.log(getComputedStyle(oTest,':before').width);//50px
        </script>

 

IE8 and browsers below do not support the getComputedStyle() method, but in IE each element with style attribute has a current Style attribute, which is an instance of CSSStyleDeclaration and contains all the calculated styles of the current element.

Computing style in obj. current Style [style] attribute does not output collection style, and the color and percentage settings are not converted, but output as-is.

        <style type="text/css">
            #test{
                background-color: #ff0;
            }
        </style>
        <div id="test" style="width: 30%;height: 200px;"></div>
        <script type="text/javascript">
            var oTest = document.getElementById('test');
            
            //Standard browsers will report errors. IE Normal display
            console.log(oTest.currentStyle.backgroundColor);//#ff0
            console.log(oTest.currentStyle.width);//30%
            console.log(oTest.currentStyle.height);//200px
        </script>

 

Compatibility Writing

        <style type="text/css">
            #test{
                background-color: #ff0;
            }
        </style><div id="test" style="width: 30%;height: 200px;"></div>
        <script type="text/javascript">
            function getCSS(obj,attribute){
                return  window.getComputedStyle ? getComputedStyle(obj)[attribute] : obj.currentStyle[attribute];
            }
            
            var oTest = document.getElementById('test');
            console.log(getCSS(oTest,'width'));//The calculated absolute value
            console.log(getCSS(oTest,'height'));//200px
        </script>

 

Dynamic Style

Dynamic style includes two situations: one is to insert an external style sheet through < link > elements, the other is to insert an internal style through < style > elements.

        <script type="text/javascript">
            //Dynamic Loading of External Styles
            function loadLinkCSS(urlData){
                loadLinkCSS.mark = 'load';//Mark whether the program has been executed
                var linkCSS = document.createElement("link");
                linkCSS.rel = "stylesheet";
                linkCSS.type = "text/css";
                linkCSS.href = urlData;//Path setting
                var oHead = document.getElementsByTagName('head')[0];
                oHead.appendChild(linkCSS);
            }
            
            //Dynamic Loading Internal Styles
            //The method is based on IE8 Errors are reported in browsers below because IE8 The following browsers will<style>As a special node, access to its child nodes or settings is not allowed. innerHTML attribute
            function loadStyleCSS(str){
                loadStyleCSS.mark = 'load';//Mark whether the program has been executed
                var styleCSS = document.createElement("style");
                styleCSS.type = "text/css";
                styleCSS.innerHTML = str;
                var head = document.getElementsByTagName('head')[0];
                head.appendChild(styleCSS); 
            }
        </script>

  

When dynamically inserting internal styles, there are compatibility problems. There are two compatibility solutions:

  1. IE browser supports accessing and modifying the cssText attribute of the CSSStyleSheet object of the element. Similar effects can be achieved by modifying the cssText attribute.
  2. Scope elements are Microsoft's own definition. In IE8 and below browsers, <style> element is a scoped element. If the string inserted through innerHTML begins with a scoped element, then IE8 and below browsers delete the element before parsing the string.
        <script type="text/javascript">
            //Compatibility Writing of Dynamic Loading Internal Styles
            //IE Browsers support accessing and modifying elements CSSStyleSheet Object cssText Attribute. Similar effects can be achieved by modifying this attribute
            function loadStyleCssCompatA(str){
                loadStyleCssCompatA.mark = 'load';//Mark whether the program has been executed
                var styleCSS = document.createElement("style");
                styleCSS.type = "text/css";
                try{
                    styleCSS.innerHTML = str;
                }catch(ex){
                    styleCSS.styleSheet.cssText = str;
                }
                var head = document.getElementsByTagName('head')[0];
                head.appendChild(styleCSS); 
            }
            
            //Compatibility Writing of Dynamic Loading Internal Styles II
              //stay IE8 In the following browsers, style An element is an element without scope.
            //If passed innerHTML Inserted strings begin with a scoped element, so IE8 The following browsers delete the element before parsing the string
            function loadStyleCssCompatB(str){
                loadStyleCssCompatB.mark = 'load';
                var styleCSS = document.createElement("div");
                styleCSS.innerHTML = '_' + '<style>' + str+'</style>';
                styleCSS.removeChild(div.firstChild);
                var oHead = document.getElementsByTagName('head')[0];
                oHead.appendChild(styleCSS.firstChild); 
                styleCSS = null;
            }
        </script>

 

CSS Module Detection

CSS rules are developing too fast and new modules are emerging in endlessly. Different versions of different browsers support CSS modules differently. Sometimes, you need to know whether the current browser supports a module, which is called "CSS module detection";

A more general approach is to determine whether an attribute value of a style object of a DOM element is a string. If the CSS attribute does exist, a string is returned. Even if the property is not actually set, an empty string is returned. If this property does not exist, undefined is returned

The CSS. support () method returns a Boolean value indicating whether a CSS rule is supported; safari and IE browsers do not.

        <div id="test"></div>
        <script>
            var oTest = document.getElementById('test');
            
            //CSS Module Detection
            //IE9 The following browsers and safari Return undefined,All other browsers return'',
            //therefore IE9 The following browsers and safari I won't support it animation
            console.log(oTest.style.animation);    
            
            //IE and firefox Browser Return undefined,chrome and safari Browsers all return'',
            //therefore IE and firefox Browser does not support WebkitAnimation
            console.log(oTest.style.WebkitAnimation);
            
            //safari and IE Browser does not support,
            //chrome Return true
            console.log(CSS.supports('transition','1s'));//true
        </script>

 

Reference material

  God's explanation is clearer, and his other essays are also very good., http://www.cnblogs.com/xiaohuochai/p/5837478.html

Keywords: Javascript Attribute IE Firefox

Added by timclaason on Mon, 08 Jul 2019 01:04:39 +0300