почему this.style[property]
получить пустую строку? мой код:почему javascript this.style [свойство] возвращает пустую строку?
<!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'. –
'elem.style' обращается к свойству стиля *, который имеет элементы. – pimvdb