原生js获取元素样式值

在学习js初期,就一直有一个疑问,获取元素样式的值,不是直接使用
obj.style.left之类的就可以得到了吗?可是使用这样的方式,有的时候能够获取得到,有的时候又不能获取,一直疑惑不已,但是由于以前学习态度的问题,也没有深究,今天专门花了点时间整理了一下这方面的知识。

样式

首先,我们要明确样式的种类有以下三种

  • 内联样式: 也就是行内样式,直接写在DOM元素的style属性中
  • 嵌入样式: 写在html页面中的<style></style>中的样式
  • 外部样式: 由link标签引入的css文件中的样式
    优先级:内联 > 嵌入 > 外部

首先,先写一个例子来测试一下通过style方法获取元素样式的值,思路是,一个样式写在行内,一个样式写在style标签中,一个样式由link引入

<head>
    <meta charset="UTF-8">
    <title>get style</title>
    <style>
        <!-- 嵌入样式 -->
        .box {
            height: 200px;
        }
    </style>
    <!-- 引入外部样式 -->
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <!-- 行内样式 -->
    <div class="box" style="width: 100px;"></div>
</body>
// index.css
.box { background-color: orange; }
// javascript
var box = document.getElementsByClassName('box')[0];
console.log(box.style.width);
console.log(box.style.height);
console.log(box.style.backgroundColor);

得到的结果为:

'100px'
''
''

因此我们可以看到height值和backgroundColor值没有被获取到,所以我们得到以下结论:
style只能获取行内样式的值,无法获取嵌入式样式和外部样式的值

那么嵌入式样式和外部样式的值应该怎么办呢,看下面代码

// currentStyle: IE下获取元素样式的值
if ( box.currentStyle ) {
    console.log( 'this is IE.' );
    console.log( box.currentStyle.width );
    console.log( box.currentStyle.height );
    console.log( box.currentStyle.backgroundColor );
} else {
    // chorme and firefox
    console.log( document.defaultView.getComputedStyle(box, false).width );
    console.log( document.defaultView.getComputedStyle(box, fasle).height );
    console.log( document.defaultView.getComputedStyle(box, false).backgroundColor );
}

输出结果

'this is IE.'
'100px'
'200px'
'orange'

分别在IE, chrome, firefox下测试一下,最后都能够获取所有的属性。非常好,于是我们可以得出结论
获取元素样式值的最佳方式,就是通过obj.currentStyle 或者
document.defaultView.getComputedStyle( obj, false ) 的方式,其中前者适用于IE,后者适用于chrome和Firefox

因此我们可以写一个获取元素样式值的方法

var getStyle = function(obj, key) {
    return obj.currentStyle ? obj.currentStyle[key] : document.defaultView.getComputedStyle( obj, false )[key];
}




转载于:https://www.cnblogs.com/chenmingchao/p/7427304.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值