js 获取DOM元素样式

    HTML的样式写入方法有:1、行内样式;2、内嵌样式;3、外联样式表。

  1.     行内样式:一般是用style写在dom元素上的,例如:<div style='height:200px;'></div>;
  2.     内嵌样式:一般是用style写在head标签内的。<style type='text/css'></style>;
  3.     外联样式:一般是用link标签或者是import引入的。但import引入的时候一定要放在style标签内。

    获取样式:

    一、ele.style

            通过这种方式只能获取到写在行内的样式。其他两种是获取不到的。例如:

            var con = document.getElementById("con");    con.style.height;    //只能获取到写在行内的height值。

    二、ele.getComputedStyle  (只读)

     可以获取到当前元素所使用到额最终的css属性值,返回是一个css样式声明对象。

     用法:var style = window.getComputedStyle(dom,[pseudoElt]);

     dom 用于获取计算样式的Element   pseudoElt   指定一个要匹配的伪元素的字符串。必须对普通元素省略(或null)

例如:
        <div class="a" style="height: 300px;"></div>
        <script type="text/javascript">
	    var a = document.getElementsByClassName("a")[0];
	    var con = window.getComputedStyle(a);
	    console.log(con)
        </script>
    得到的结果如下:
如果想获取到其中的高度值(height)则可以:var H = window.getComputedStyle(a).height;   这样就可以拿到高度值。

三、ele.currentStyle

        在旧版本的IE浏览器想要达到和getComputedStyle的功能。可以使用currentStyle方法

        例如:var test = document.getElmentById('test');

                    console.log(test.currentStyle.color)    //可以拿到id为test的元素的字体颜色

四、getPropertyValue获取CSS样式的直接属性名称

    用法:
 window.getComputedStyle(element, null).getPropertyValue(属性);
    例如:var test = document.getElmentById('test');
    window.getComputedStyle(test, null).getPropertyValue("background-color");
    注意:属性名不支持驼峰格式,IE6-8不支持该方法,需要使用下面的方法

五、getAttribute与getPropertyValue类似,有一点的差异是属性名驼峰格式

    例子:

    var test = document.getElementById('test');

    window.getComputedStyle(test, null).getPropertyValue("backgroundColor");

    注意:该方法只支持IE6-8
六、使用jquery.js来获取样式

    其实jq获取元素的样式也是对ele.currentStyle和ele.getComputedStyle、getPropertyValue、getAttribute 进行了整体的封装。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值