document.defaultView.getComputedStyle

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

使用:document.defaultView.getComputedStyle(a, b);
a这对象是要想要获取的对象。
b,伪类,若果不是则为null。
div{     width: 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);

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

猜你喜欢

转载自www.cnblogs.com/jiunie/p/10940546.html