document.defaultView.getComputedStyle

我们在使用js过程中,有时候需要获取对象的宽度,如果对象本身是由内容撑开。宽度未知的情况,有一个强大的方法document.defaultView.getComputedStyle()可以获取对象的css样式;他返回的是一个CSS样式对象。

使用:document.defaultView.getComputedStyle(a, b);
a这对象是要想要获取的对象。
b,伪类,若果不是则为null。
div{      100px;     font-size: 15px; }
<div>遇见他,她变得很低很低,低到尘里,可她心里是欢喜的,从尘埃里开出花来</div>
var d=document.getElementsByTagName("div")[0]; 
console.log(document.defaultView.getComputedStyle(d,null).height);
console.log(document.defaultView.getComputedStyle(d,null).fontSize);

 1 function getXY(mm){
 2   var x=0,y=0;
 3   if(mm.currentStyle){ //IE 下
 4     x=mm.currentStyle.left;
 5     y=mm.currentStyle.top;
 6   }else if (document.defaultView.getComputedStyle){ //getComputedStyle() -- DOM提供的方法,火狐、谷歌、IE9支持
 7     x=document.defaultView.getComputedStyle(mm,null).left;
 8     y=document.defaultView.getComputedStyle(mm,null).top;
 9   }
10   alert("("+x+","+y+")");
11 }