getComputedStyle和currentStyle的使用方法
getComputedStyle可获取当前元素的所有css属性,返回的是一个[object CSSStyleDeclaration]对象,用法为:
var Div=document.getElementById('div');
var str=window.getComputedStyle(Div,null);//返回的是一个对象[object CSSStyleDeclaration],window可写可不写
alert(str.height);
//console.log(window.getComputedStyle(Div,null));可打印出当前对象所有的属性
如上,它有两个参数,第二个参数可写可不写,但是它只能在主流浏览器下(chrome,Safari,火狐...)使用,它只能读取,不能更改,并且返回复合属性border时,在chrome下可返回(格式为:0px none rgb(0, 0, 0)),在火狐下返回空(其余我没有测试)
currentStyle是只有IE浏览器才能识别的,它也可以获取当前元素的所有css属性,返回的是一个[object CSSStyleDeclaration]对象,用法为:
var str=Div.currentStyle;//返回的是CSSStyleDeclaration实例
console.log(str.width);
它调用复合属性border时,返回的是undefined,如图:
为了使IE浏览器和主流浏览器都能正常获取当前元素的所有属性,要使用兼容性的写法:
//兼容性写法
var str=Div.currentStyle||getComputedStyle(Div,null);
alert(str.width);