Search code examples
javascriptjquerycssstyles

why javascript this.style[property] return an empty string?


why this.style[property] get an empty string? my code is:

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <style type="text/css">
        #test{
            height:100px;
        }
        .tclass{
            width:100px;
        }
    </style>
    <script type="text/javascript">
        function $(ID){
            var element=document.getElementById(ID||'nodId');
            if(element){
                element.css=css;
            }
            return element;
        }

        function css(prop,value){
            if(value==null){
                return this.style[prop];
            }
            if(prop){
                this.style[prop]=value;
            }
            return true;
        }

        window.onload=function(){
            var element=$("test");
            alert(element.css("height")+","+element.css("width")+","+element.css("background"));

            //alert ,,#ccc
        };
    </script>
</head>
<body>
    <div id="test" style="background:#CCC;" class="tclass">Test</div>
</body>
</html>

this code alert ,,#ccc,but i want get 100px,100px,#ccc,what's wrong with me? who can help me?

update

i changed the css function,now it can work well:

    function css(prop,value){
        if(value==null){
            var b = (window.navigator.userAgent).toLowerCase();
            var s;
            if(/msie|opera/.test(b)){
                s = this.currentStyle
            }else if(/gecko/.test(b)){
                s = document.defaultView.getComputedStyle(this,null);
            }
            if(s[prop]!=undefined){
                return s[prop];
            }
            return this.style[prop];
        }
        if(prop){
            this.style[prop]=value;
        }
        return true;
    }

Solution

  • The .style property is for getting styles that were placed directly on the element. It doesn't compute styles from your stylesheets.

    You may use getComputedStyle() instead:

    const myElement = document.getElementById('myId');
    const style = getComputedStyle(myElement);
    console.log(style.height); // "100px"