您的位置:首页 > Web前端 > CSS

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

2014-06-03 23:12 507 查看
在获取某些元素的样式值时需要用到不同的兼容方法来获取,如获取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];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐