JavaScript get CSS inline style and external style

There is a global method getComputedStyle in the DOM standard, which can get the current object style rule information. For example, getComputedStyle(obj,null).paddingLeft can get the left inner margin of the object. However, IE does not support this method. It has its own implementation method, that is, currentStyle, which is different from the global method getComputedStyle. It exists as a DOM element attribute, such as obj.currentStyle.paddingLeft. In IE, the left inner margin of the object is obtained. The compatibility method is as follows:

return window.getComputedStyle ? window.getComputedStyle(obj,null).paddingLeft : obj.currentStyle.paddingLeft;

The case code is as follows

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Native JS Realization jQuery Fade in / out effect</title>
        <style type="text/css">
            #testBox {
                width: 175px;
                height: 175px;
                background-color: #009E94;
                opacity: 0.5;
            }
        </style>
        <script type="text/javascript">
            window.onload = function() {
                var testBox = document.getElementById("testBox");
                var opacity = window.getComputedStyle ? window.getComputedStyle(testBox,null).opacity : testBox.currentStyle.opacity;
                console.log(opacity)
            }
        </script>
    </head>
    <body>
        <div id="testBox"></div>
    </body>
</html>

We encapsulate it, and the encapsulated code is shown below.

window.onload = function() {
    var testBox = document.getElementById("testBox");
    var opacity = getStyle(testBox,"opacity");
    console.log(opacity)
}
function getStyle(obj, prop) {
    if(window.getComputedStyle) {
        return window.getComputedStyle(obj,null)[prop];
    } else if(obj.currentStyle) {
        return obj.currentStyle[prop];
    }
    return null;
}

Summary: non in line acquisition method based on IE browser: use obj.currentStyle["attr"]; non in line acquisition method based on non IE browser, such as Firefox and Google: use window. Getcomputedstyle (obj) [attr "]

Remember: non inline style acquisition method, can only be acquired but not set.

 

Keywords: IE Attribute JQuery Javascript

Added by yepster123 on Wed, 13 Nov 2019 21:26:51 +0200