zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    java-学习8
    java-学习7
    java-学习6
    html----h1-6标签
    jquery.cookie介绍和用法
    java-学习5
    java-学习4
    Eclipse里的代码光标变成一个黑色块
    java-学习3(jdk-环境配置)
    箭头函数无法使用this的解决方法
  • 原文地址:https://www.cnblogs.com/qianxunpu/p/7290456.html
Copyright © 2011-2022 走看看