zoukankan      html  css  js  c++  java
  • 知道一个div的宽高背景色,如何不通过写在行间样式的办法更改样式?currentStyle(只兼容ie),getComeputedStyle(兼容)-->获取非行间样式

    知道一个div的宽高背景色,如何不通过写在行间样式的办法更改样式?currentStyle(只兼容ie),getComeputedStyle(兼容ie9以上)-->获取非行间样式

     (1)currentStyle 仅支持ie

    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>返回值</title>
    </head>
    <style type="text/css">
    #div1{width: 200px;height: 200px;background: red;}
    </style>
    <script type="text/javascript">
    window.onload=function(){
        var oDiv=document.getElementById('div1');
        alert(currentStyle.width);
    
    }
    </script>
    <body>
    <div id="div1"></div>
    </body>
    </html>

     (2)getComputedStyle,有两个参数,第二个参数可以为任何数,不起实质性作用。

    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>返回值</title>
    </head>
    <style type="text/css">
    #div1{width: 200px;height: 200px;background: red;}
    </style>
    <script type="text/javascript">
    window.onload=function(){
        var oDiv=document.getElementById('div1');
        alert(getComputedStyle(oDiv,false).width);
    
    }
    </script>
    <body>
    <div id="div1"></div>
    </body>
    </html>

    兼容所有浏览器的写法

    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>返回值</title>
    </head>
    <style type="text/css">
    #div1{width: 200px;height: 200px;background: red;}
    </style>
    <script type="text/javascript">
    window.onload=function(){
        var oDiv=document.getElementById('div1');
        if(oDiv.currentStyle){
            //ie
            alert(oDiv.currentStyle.width);
        }
        else{
            //ff
            alert(getComputedStyle(oDiv,false).width)
        }
    
    }
    </script>
    <body>
    <div id="div1"></div>
    </body>
    </html>

    但是,在实际应用过程中,这样的写法有些复杂,通过封装一个函数来写,将来用的时候再调用。

    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>返回值</title>
    </head>
    <style type="text/css">
    #div1{width: 200px;height: 200px;background: red;}
    </style>
    <script type="text/javascript">
    function getStyle(obj,name){
        if(obj.currentStyle){
            return obj.currentStyle[name];
        }
        else{
            return getComputedStyle(obj,false)[name];
        }
    }
    window.onload=function(){
        var oDiv=document.getElementById('div1');
        alert(getStyle(oDiv,'width'));
    
    }
    </script>
    <body>
    <div id="div1"></div>
    </body>
    </html>
    衣带渐宽终不悔,为伊消得人憔悴,憔悴半天也没用,还是努力起来人富贵
  • 相关阅读:
    分布式事务解决方案1--使用Atomikos分布式事务(事务强一致方案)
    SringBoot集成Sharding-Jdbc 实践
    Sharding-Jdbc简介
    Mycat+haproxy中使用keepalived保障haproxy的高可用
    Angular CLI
    背压(Backpressure)机制
    Function.identity()
    解决Error: ENOENT: no such file or directory, scandir 安装node-sass报错
    Reactor flatMap
    Reactor map
  • 原文地址:https://www.cnblogs.com/zhangjingyun/p/4561648.html
Copyright © 2011-2022 走看看