为什么JavaScript this.style [property]返回一个空字符串?
问题描述:
为什么this.style[property]
得到一个空字符串?我的代码是:为什么JavaScript 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;
}
答
的元素没有指定一个CSS高度或宽度。
请注意,您正在尝试获取“请求”尺寸,而不是实际尺寸。因此输出是正确的。
如果您想获得有效大小,请使用jQuery width()
和height()
方法。请参阅http://api.jquery.com/width/
那么,DOM元素没有'style'属性。所以你不能得到他们的'样式'属性。 – 2012-02-25 14:24:25
'elem.style'正在访问元素具有的样式*属性*。 – pimvdb 2012-02-25 14:26:00