Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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;
    }
like image 387
artwl Avatar asked Feb 25 '12 14:02

artwl


2 Answers

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"
like image 99
user1106925 Avatar answered Sep 30 '22 03:09

user1106925


The elements do not have a CSS height or width specified.

Note that you are trying to get the "requested" sizes, not the actual sizes. The output therefore is correct.

If you want to get the effective sizes, use the jQuery width() and height() methods. See http://api.jquery.com/width/

like image 45
Has QUIT--Anony-Mousse Avatar answered Sep 30 '22 03:09

Has QUIT--Anony-Mousse