为什么 javascript this.style[property] 返回一个空字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9444751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why javascript this.style[property] return an empty string?
提问by artwl
why this.style[property]
get an empty string? my code is:
为什么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>
this code alert ,,#ccc
,but i want get 100px,100px,#ccc
,what's wrong with me? who can help me?
此代码警报,,#ccc
,但我想得到100px,100px,#ccc
,我怎么了?谁能帮我?
update
更新
i changed the css function,now it can work well:
我更改了 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;
}
回答by
The .style
property is for getting styles that were placed directly on the element. It doesn't compute styles from your stylesheets.
该.style
属性用于获取直接放置在元素上的样式。它不会从您的样式表计算样式。
See getComputedStyle()
.
回答by Has QUIT--Anony-Mousse
The elements do not have a CSS height or width specified.
元素没有指定 CSS 高度或宽度。
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 effectivesizes, use the jQuery width()
and height()
methods. See http://api.jquery.com/width/
如果您想获得有效尺寸,请使用 jQuerywidth()
和height()
方法。见http://api.jquery.com/width/