为什么 JavaScript 中的 this.style[property] 返回空字符串?

27

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

<!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>

这段代码弹出警报:,,#ccc,但我想获取的是 100px,100px,#ccc,我做错了什么?谁能帮助我?

更新

我改变了 CSS 函数,现在它可以正常工作:

    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;
    }

好的,DOM元素没有style属性。因此,您无法获取它们的style属性。 - Lightness Races in Orbit
elem.style 访问的是元素拥有的样式 属性 - pimvdb
如果您正在使用jQuery,可以使用$(this).css(property);来获取属性值,使用$(this).css(property, set);来设置属性值。 - SwiftNinjaPro
2个回答

75

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

您可以使用 getComputedStyle() 替代:

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

2

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接