zoukankan      html  css  js  c++  java
  • 获取元素的外联样式

    我们都知道在JS中,使用ele.style.width只能获取到内联样式:

    <div id="box" style="background-color: red;"></div>
            <script>
                var oDiv = document.getElementById("box")
                alert(oDiv.style.backgroundColor); //red
            </script>

    但是,将样式放在<style></style>标签里,我们获取到的就是空;

    这时候我们就需要用到getComputedStyle方法,它接受两个参数,第一个是目标元素,第二个是要选择的伪类,第二个参数如果不选择伪类,就填null:

    var oBox = document.getElementById("box");
    alert(getComputedStyle(oBox,null).width); //oBox的宽度

    但是,在IE中不支持这个方法,它有自己的方法,即currentStyle:

    var oBox = document.getElementById("box");
    alert(oBox.currentStyle.width);  //oBox的宽度

    所以,我们写一个简单的兼容函数:

                function getStyle( obj , attr ){
                    if ( window.getComputedStyle ) {
                        return getComputedStyle( obj , null )[attr];
                    }else{
                        return obj.currentStyle[attr];
                    }
                }
  • 相关阅读:
    [HDU3094]A tree game
    专题总结(博弈论)
    [ZJOI2009]染色游戏
    [AtCoder3954]Painting Machines
    异或
    种树
    [PA2014]Fiolki
    简单题
    2、JUC--CAS算法
    1、JUC--volatile 关键字-内存可见性
  • 原文地址:https://www.cnblogs.com/rongy/p/6653385.html
Copyright © 2011-2022 走看看