currentStyle与getComputedStyle

碰到一个题:获取非行间样式的方法。(先写了小的demo)

1.html文件

<head>
    <style>
        #test {
            font-size: 14px;
            line-height: 20px;
            padding: 10px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div id="test" style='color:#f00;'>我的样式</div>
</body>

 2. js

1 console.log(document.getElementById('test').style.color);
2 /* 
3     1. 把颜色的值写在style标签里的时候,console.log值为空;
4     2. 把颜色写在行内样式里时,console的值为 rgb(255, 0, 0)
5     所以,这样可以看到,document.getElementById('test').style.XXX只能拿到行内的style样式,而不能拿到内嵌的样式
6 */

 

function getStyle(obj, attr, value) {
        if (!value) {//是否set属性值
               return window.getComputedStyle ? window.getComputedStyle(obj, false)[attr] : obj.currentStyle[attr];
               //currenStyle兼容IE,getComputedStyle兼容FF,Chrome(FF未测试)
        } else {
               obj.style[attr] = value
        }
}
getStyle(document.getElementById('test'), 'color', '#a34e3f');
//如果set属性值,则写出第三个参数,如果不set的话,不写第三个参数

 

转载于:https://www.cnblogs.com/biangz/p/6392888.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值