为什么javascript this.style [property]返回一个空字符串? [英] why javascript this.style[property] return an empty string?
本文介绍了为什么javascript this.style [property]返回一个空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 this.style [property]
得到一个空字符串?我的代码是:
why this.style[property]
get an empty string? my code is:
<!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>
此代码alert ,,#ccc
但我想得到 100px,100px,#ccc
,我怎么了?谁可以帮助我?
this code alert ,,#ccc
,but i want get 100px,100px,#ccc
,what's wrong with me? who can help me?
更新
我更改了css功能它可以很好地工作:
i changed the css function,now it can work well:
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;
}
推荐答案
.style
属性用于获取直接放在元素上的样式。它不会从样式表中计算样式。
The .style
property is for getting styles that were placed directly on the element. It doesn't compute styles from your stylesheets.
请参见 getComputedStyle()
。
这篇关于为什么javascript this.style [property]返回一个空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文