JS如何获取元素样式?

上篇文章讲到如何设置元素样式,本文将继续给大家分享如何获取元素样式。

一、style,只获取标签上定义的行内样式

在这里讲的style用法包括三个:style、style.cssText和style.getPropertyValue(),直接看个例子吧:

/*CSS*/
#box{ width: 200px; height: 200px; background-color: #0f0;}
<!--HTML-->
<div id="box" style="width: 100px; background-color: #f00;"></div>
//JavaScript
var box = document.getElementById("box");
console.log(box.style.cssText);  // "width: 100px; background-color: rgb(255, 0, 0);"
console.log(box.style.width);    // "100px"
console.log(box.style.height);    // ""
console.log(box.style.getPropertyValue('background-color'));  // "rgb(255, 0, 0)"

通过上面例子我们可以看出,通过这种方式只能获取行内样式,并不能获取到CSS样式表中的样式。

二、cssRules,只获取CSS样式表中定义的样式

接着上面的例子:

//JavaScript
var sheet = document.styleSheets[0];   // 获取页面中第一个样式表
var rules = sheet.cssRules;   // 获取页面中第一个样式表中定义的所有规则,rules[0]即代表第一条规则
console.log(rules[0].style.cssText);    // "width: 200px; height: 200px; background-color: rgb(0, 255, 0);"
console.log(rules[0].style.width);    // "200px"
console.log(rules[0].style.height);    // "200px"
console.log(rules[0].style.getPropertyValue('background-color'));    // "rgb(0, 255, 0)"

可以看出,用法其实与上面类似,只不过是主体变为rules[0]而不是box,所以只能获取到样式表中的样式,而并不能获取到行内样式。

三、getComputedStyle(),获取当前元素的计算样式

以上两种方式,都具有太强的针对性,不够灵活,因为获取到的样式可能并不是当前元素最终表现出来的样式。因此,如果想要获取所有样式表层叠而来的当前元素的样式,我们就要用到getComputedStyle()方法。

依然继续前面的例子:

console.log(getComputedStyle(box).cssText);    // 注意不仅仅只打印现有样式简单的叠加覆盖结果,而是还会有很多其他样式
console.log(getComputedStyle(box).width);    // "100px"
console.log(getComputedStyle(box).height);    // "200px"
console.log(getComputedStyle(box).getPropertyValue('background-color'));    // "rgb(255, 0, 0)"

很明显,用法还是和style类似,但是通常情况下使用这种方式获取到的样式才是我们真正所需要的。

兼容性:在IE8下,getPropertyValue()、cssRules和getComputedStyle()统统都不兼容,可以分别使用style.[属性名]、rules和currentStyle的方式替代,具体用法本文将不再说明,在此也希望其他开发者放弃兼容IE8及更早版本,如今2017都快接近尾声,微软自己都早已放弃,我们何必继续再惯着那部分少量用户而折磨自己呢?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值