why javascript this.style[property] return an empty string?
本问题已经有最佳答案,请猛点这里访问。
为什么
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> |
此代码警报
更新
我更改了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; } |
请参见
元素没有指定CSS高度或宽度。
请注意,您正在尝试获取"请求的"大小,而不是实际大小。 因此输出正确。
如果要获取有效大小,请使用jQuery