zoukankan      html  css  js  c++  java
  • 原生js提取非行间样式

    js用style属性可以获得html标签的样式,但是不能获取非行间样式,如何获取css的非行间样式呢,在低版本ie我们可以用currentStyle,在其他浏览器我们可以用getComputedStyle。

    1、ie

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            #box{
                width:200px;
                height:200px;
                background: skyblue;
            }
        </style>
        <script>
            window.onload=function(){
                var box=document.getElementById("box");
                alert(box.currentStyle["width"]);       //200px
            }
        </script>
    </head>
    <body>
        <div id="box"></div>
    </body>
    </html>

    2、其他浏览器

    alert(getComputedStyle(box,false)["width"]);        //200px

    3、兼容

    <script>
            function getStyle(obj,attr){
                if(obj.currentStyle){
                    return obj.currentStyle[attr];
                }else{
                    return getComputedStyle(obj,false)[attr];
                }
            }
    
            window.onload=function(){
                var box=document.getElementById("box");
                alert(getStyle(box,"width"));    //兼容ie及其他浏览器
            } 
        </script>

    4、获取及设置非行间样式

    <script>
            function getStyle(obj,attr,value){
                if(arguments.length==2){         //根据参数个数执行相应操作
                    if(obj.currentStyle){
                        return obj.currentStyle[attr];
                    }else{
                        return getComputedStyle(obj,false)[attr];
                    }
                }else{
                    obj.style[attr]=value;         //这里需要注意,使用obj.style.attr无效
                }
                
            }
    
            window.onload=function(){
                var box=document.getElementById("box");
                getStyle(box,"backgroundColor","yellowgreen");          //把盒子的背景颜色设置成黄绿色
                alert(getStyle(box,"width"));      //弹出盒子的宽度200px
            } 
        </script>
  • 相关阅读:
    ACM士兵排队
    ACM两个士兵打牌
    ACM平衡的括号
    ACM复合词
    ACM第二次比赛( C )
    ACM比赛(第二次A)
    ACM比赛(进制转换)
    ACM比赛(11462 Age Sort)
    ACM比赛
    hdu 1241 Oil Deposits(DFS求连通块)
  • 原文地址:https://www.cnblogs.com/xlj-code/p/6427510.html
Copyright © 2011-2022 走看看