getcomputedStyle()获取电脑计算后的样式
div{
width: 200px;
height: 200px;
background: red;
}
<div></div>
var oDiv = document.getElementsByTagName ( 'div' )[0];
console.log( getComputedStyle( oDiv ) );
![](https://img.haomeiwen.com/i9948454/dc16d4985548bb4c.png)
得到其中一个属性值:
var oDiv = document.getElementsByTagName ( 'div' )[0];
console.log( getComputedStyle( oDiv ).width );
得到是200px;
如果没有给DIV设置宽度获取到的是窗口的宽度;div是块级元素
![](https://img.haomeiwen.com/i9948454/3fc58e4419e0b6bb.png)
IE8及以下不兼容;
var oDiv = document.getElementsByTagName( 'div' )[0];
// console.log( getComputedStyle( oDiv ).width );
var width;
if( window.getComputedStyle ){ //判断window有没有这个函数
width = window.getComputedStyle(oDiv).width; //如果有用这个方法
} else {
width = oDiv.currentStyle.width;//如果没有用这个方法
}
console.log( width );
通用函数
function getStyle( obj , attr ){
if( window.getComputedStyle ){ //判断window有没有这个函数
return window.getComputedStyle(obj)[attr]; //如果有用这个方法 []我们下面传的是一个字符串如果用[]
} else {
return obj.currentStyle[attr];//如果没有用这个方法
}
}
//
function getStyle( obj , attr ){
if( window.getComputedStyle ){ //判断window有没有这个函数
return window.getComputedStyle(obj)[attr]; //如果有用这个方法 []我们下面传的是一个字符串如果用[]
} else {
return obj.currentStyle[attr];//如果没有用这个方法
}
三目写法 return要写在前面
return window.getComputedStyle ? window.getComputedStyle(obj)[attr] : obj.currentStyle[attr];
}
另一种写法:
function getStyle( obj ){
if( obj.currentStyle ){ //假如能获取到 就是IE浏览器 得到的是对象 就是真
return obj.currentStyle;
} else {
return getComputedStyle( obj );
}
用||来写
return obj.currentStyle || getComputedStyle( obj );
}
例题:
var objWidth = parseInt ( getStyle( oDiv , 'width' ));
console.log( objWidth );
oDiv.onclick = function (){
this.style.width = parseInt ( getStyle( oDiv , 'width' )) + 200 + 'px';
}
每点一次增加200px
![](https://img.haomeiwen.com/i9948454/4e680843fdaf1983.png)
![](https://img.haomeiwen.com/i9948454/bf2c2f40ac798ab1.png)
![](https://img.haomeiwen.com/i9948454/0c54a2a41fd26160.png)
var objWidth = parseInt ( getStyle( oDiv , 'width' ));
console.log( objWidth );
oDiv.onclick = function (){
this.style.left = parseInt ( getStyle( oDiv , 'left' )) + 200 + 'px';
}
![](https://img.haomeiwen.com/i9948454/aac5040032ac2cc2.png)
![](https://img.haomeiwen.com/i9948454/01a9d56f6aeec214.png)
![](https://img.haomeiwen.com/i9948454/95b28cba91361439.png)
网友评论