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>
  • 相关阅读:
    查看sql 语句io执行情况
    MVC API 返回json 对象,使用netjson 返回
    微信支付——调用微信客户端支付之【服务端】开发详解
    React-Native hello word 搭建及新手常见问题
    PD中将Comment 从Name复制值
    Redis_DataType
    ConCurrent in Practice小记 (1)
    单链表是否存在环的检测(快慢指针法)
    开园第一天
    我希望……
  • 原文地址:https://www.cnblogs.com/xlj-code/p/6427510.html
Copyright © 2011-2022 走看看