爲什麼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;
}
那麼,DOM元素沒有'style'屬性。所以你不能得到他們的'樣式'屬性。 – 2012-02-25 14:24:25
'elem.style'正在訪問元素具有的樣式*屬性*。 – pimvdb 2012-02-25 14:26:00