关于jquery:为什么javascript this.style [property]返回空字符串?

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

本问题已经有最佳答案,请猛点这里访问。

为什么this.style[property]得到一个空字符串? 我的代码是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html>
<head>
    Demo
    <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
        };
   
</head>
<body>
    Test
</body>
</html>

此代码警报,,#ccc,但是我想获取100px,100px,#ccc,我怎么了? 谁能帮我?

更新

我更改了CSS功能,现在可以正常使用了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    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;
    }


.style属性用于获取直接放置在元素上的样式。 它不会从样式表中计算样式。

请参见getComputedStyle()


元素没有指定CSS高度或宽度。

请注意,您正在尝试获取"请求的"大小,而不是实际大小。 因此输出正确。

如果要获取有效大小,请使用jQuery width()height()方法。 参见http://api.jquery.com/width/