JavaScript动态获取Style样式笔记

借鉴了鑫神的博客,关于动态的获取style



jquery的话 直接 通过  .css('属性') 这样的方法就能获取



如果通过原生态的javascript话 


测试环境  IE11 ,FireFox 52.0 ,Chrome 56.0


兼容写法

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style>
            div{
            width:300px;
            height: 300px;
            background:green;
            border-bottom: 1px solid black;
            }
        </style>
    </head>
    <body>
        <div>1111111</div>
    </body>
    <script>

        //以下方法 兼容 IE11 chrome  firefox
         var div=document.getElementsByTagName("div")[0];
        //必须采用驼峰式命名
        console.log(getComputedStyle(div)['borderBottomWidth']);
        //getPropertyValue使用了非驼峰式命名
        console.log(getComputedStyle(div).getPropertyValue("border-bottom-width"));
    </script>
</html>

这里用到了  getComputedStyle这个方法 注意  获取属性的 驼峰式和非驼峰式的区别


俗话说的好,自古“IE”奇葩多,IE下还能这样写,仅仅只能在IE下

console.log(div.currentStyle['borderBottomWidth']);

好了web发展到现在难免还有一些老用户(IE8,IE9),最终给出一个兼容写法


 function getStyle(object,attr){
            return object.currentStyle?object.currentStyle[attr]:getComputedStyle(object)[attr];
        }


大功告成,之前一直习惯了 jquery的css()方法,今天研究了一番做下笔记



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值