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>
this code alert ,,#ccc
,but i want get 100px,100px,#ccc
,what's wrong with me? who can help me?
update
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;
}
The .style
property is for getting styles that were placed directly on the element. It doesn't compute styles from your stylesheets.
You may use getComputedStyle()
instead:
const myElement = document.getElementById('myId');
const style = getComputedStyle(myElement);
console.log(style.height); // "100px"
The elements do not have a CSS height or width specified.
Note that you are trying to get the "requested" sizes, not the actual sizes. The output therefore is correct.
If you want to get the effective sizes, use the jQuery width()
and height()
methods. See http://api.jquery.com/width/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With