js获取元素宽度高度

 第一种情况就是宽高都写在样式表里,就比如#div1{width:120px;}。这中情况通过#div1.style.width拿不到宽度,而通过#div1.offsetWidth才可以获取到宽度。
第二种情况就是宽和高是写在行内中,比如style="width:120px;",这中情况通过上述2个方法都能拿到宽度
小结,因为id.offsetWidth和id.offsetHeight无视样式写在样式表还是行内,所以我们获取元素宽和高的时候最好用这2个属性。注意如果不是写在行内style中的属性都不能通过id.style.atrr来获取。
 <script type="text/javascript">
    function $(id){
    return document.getElementById(id)
    }
    function getHeight() {
    alert($("hidden").offsetHeight + "px");
    $("pinglun").style.height=$("hidden").offsetHeight + "px";
    }
    window.onload = function() {
    getHeight();
    }
    </script>

<style>
    #hidden { width:100px; background:#99CC00; height:400px; float:left}
    #pinglun { width:500px; height:auto; background:#FFCCCC; float:left; margin-left:5px;}
    </style>

    <div id="hidden">hidden</div>
    <div id="pinglun" >评论数据载入中&hellip;&hellip;</div>

 获取元素样式在实际应用中一定常用到, 若是纯粹html中, 直接elem.style.attr就可获取, 但更多的时候我们是要从css中获取元素的最终样式属性.所以, 我们得利用ie的currentstyle和w3c的getpropertyvalue获取.
elem.style.attr获取样式的方法就不说了. 先来看currentstyle方法, 此对象ie专属, 代表了在全局样式表、内嵌样式和 html 标签属性中指定的对象格式和样式. ie下通过它, 就可以获取元素的css属性值.
而针对其他标准浏览器, w3c也提供了一个方法getpropertyvalue, 此方法, 稍有点复杂, 首先要通过document.defaultview.getcomputedstyle获得css的样式对象, 然后通过该对象的getpropertyvalue获取属性值.

 

function attrstyle(elem,attr){
 if(elem.style[attr]){
  //若样式存在于html中,优先获取
  return elem.style[attr];
 }else if(elem.currentstyle){
  //ie下获取css教程属性最终样式(同于css优先级)
  return elem.currentstyle[attr];
 }else if(document.defaultview && document.defaultview.getcomputedstyle){
  //w3c标准方法获取css属性最终样式(同于css优先级)
  //注意,此法属性原格式(text-align)获取的,故要转换一下
  attr=attr.replace(/([a-z])/g,'-$1').tolowercase();
  //获取样式对象并获取属性值
  return document.defaultview.getcomputedstyle(elem,null).getpropertyvalue(attr);
 }else{
  return null;
 }
}

function getStyle(e,n){
  if(e.style[n]){
   return e.style[n];
  }
  else if(e.currentStyle){
   return e.currentStyle[n];
  }
  else if(document.defaultView && document.defaultView.
 getComputedStyle){
   n = n.replace(/([A-Z])/g,"-$1");
   n = n.toLowerCase();
   var s = document.defaultView.getComputedStyle(e,null);
   if(s)
    return s.getPropertyValue(n);
  }
  else
   return null;
 } 

如果样式width:auto或者百分比。上述可能出错需要用javascript重新确认width

posted @ 2013-08-04 21:49  hlp鹏  阅读(2126)  评论(0编辑  收藏  举报