getComputedStyle与currentStyle的区别

先看个例子

<!DOCTYPE html>
<html lang="en">
<script src="miaov.js"></script>
<head>
    <meta charset="UTF-8">
    <title>return返回值</title>
    <style>
        #div1{
            width:50px;
            height:50px;
            background-color: greenyellow;
        }
    </style>
</head>
<body>
<button id="btn">按钮</button>
<div id="div1" style="400px;"></div>
</body>
<script>
//    alert(typeof fn1());
//
//    function fn1(){
//        return 'miaov';
//    }
//
//    alert(typeof fn2(10)(20));
//    function fn2(a){
//        return function(b){
//            alert(a+b);
//        }
//    }
  /*  $(function(){});

    function $(v){
        if(typeof v==='function'){
            window.onload = v;
        }else if(typeof v=='string'){
            return document.getElementById(v);
        }else if(typeof v==='object'){
            return v;
        }
    }*/
  $(function(){
      $("btn").onclick = function(){
          $('div1').style.width='300px';

        // alert($('div1').style.width);  是行内样式才可以获取到宽度

         // alert(getComputedStyle($('div1')).width); //300px
          //获取到的是计算机计算后的样式,在低于IE9不起作用
          //alert($('div1').currentStyle.width); 在IE低版本6,7,8下才能用,其他浏览器反而失效

          //兼容性的写法
          if($('div1').currentStyle){
                alert($('div1').currentStyle.width);
          }else{
              alert(getComputedStyle($('div1')).width);
          }
      }

  });
  //调用getStyle
alert(getStyle($('div1'),'height'));
  function getStyle(obj,attr){
      if(obj.currentStyle){
          return obj.currentStyle[attr];
      }else{
          return getComputedStyle(obj)[attr];
      }

//三目运算
        // return obj.currentStyle ? obj.currentStyle[attr]: getComputedStyle(obj)[attr];

  }
//不要获取未设置的样式
   // 不要获取复合样式(如:background)
</script>
原文地址:https://www.cnblogs.com/qianxunpu/p/7290456.html