笔记-[1]-获取元素样式值的兼容性问题解决方法。

在获取某些元素的样式值时需要用到不同的兼容方法来获取,如获取div的height的值

代码:

<html>

<style>

#div1{width:100px;height:100px;background:red;}//获取非行间样式

</style>

<div id="div1">

</div>

</html>

JS兼容版获取样式值:

<script type="text/javascript">

window.onload=function(){

  //定义一个function getStyle

  var oDiv=document.getElementById('div1');

  function getStyle(obj,attr){

      if(obj.currentStyle){

      return obj.currentStyle[attr];//ie下

      }else{

      return getComputedStyle(obj,false)[attr];//非ie下

      }

  }

  //调用方法获取值

  getStyle(oDiv,'width');//100px

}

</script>

 

 

/*主要的兼容代码*/

function getStyle(obj,attr){

      if(obj.currentStyle){

      return obj.currentStyle[attr];//ie下

      }else{

      return getComputedStyle(obj,false)[attr];//非ie下

      }

}

或者

return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj,false)[attr];

posted @ 2014-06-03 23:12  宇宙第一小菜鸟  阅读(172)  评论(0编辑  收藏  举报