【问题标题】:why javascript this.style[property] return an empty string? [duplicate]为什么 javascript this.style[property] 返回一个空字符串? [复制]
【发布时间】:2012-03-15 17:30:38
【问题描述】:

为什么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 属性。
  • elem.style 正在访问元素所具有的样式 property
  • 如果你使用jquery,可以$(this).css(property);获取属性值,$(this).css(property, set);设置值。

标签: javascript jquery css styles


【解决方案1】:

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

getComputedStyle()

【讨论】:

    【解决方案2】:

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

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

    如果您想获得 有效 尺寸,请使用 jQuery width()height() 方法。见http://api.jquery.com/width/

    【讨论】:

      猜你喜欢
      • 2013-04-09
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 2019-03-12
      相关资源
      最近更新 更多