lý do tại sao this.style[property]
nhận chuỗi rỗng? mã của tôi là:tại sao javascript this.style [property] trả về một chuỗi rỗng?
<!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>
mã này cảnh báo ,,#ccc
, nhưng tôi muốn có được 100px,100px,#ccc
, có chuyện gì với tôi? ai có thể giúp tôi?
cập nhật
tôi đã thay đổi chức năng css, bây giờ nó có thể làm việc tốt:
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;
}
Vâng, các phần tử DOM không có thuộc tính 'kiểu'. Vì vậy, bạn không thể nhận được thuộc tính 'style' của họ. –
'elem.style' đang truy cập thuộc tính * kiểu * mà các phần tử có. – pimvdb