目录
【兼容性封装】currentStyle和getComputedStyle
非 VIP 用户可前往公众号“前端基地”进行免费阅读,文章链接如下:
10告别样式兼容难题!三招教你吃透JavaScript元素样式获取技巧
getComputedStyle获取元素css样式
在 JavaScript 操作网页元素样式时,对象.style.属性 这种方式只能设置和读取行内样式,无法读取选择器中设置的样式。为了获取元素的完整计算样式,我们可以使用 getComputedStyle 方法。
getComputedStyle 是现代标准浏览器(如 Chrome、Firefox、Safari 等)以及 IE9 及以上版本支持的方法,用于获取元素的计算样式。不过,IE6、7、8 等低版本 IE 浏览器并不支持该方法。
以下内容展示了如何使用 getComputedStyle 方法获取元素的样式,示例代码如下:
css部分:
<style type="text/css">
.box{
width: 200px;
height: 50px;
background-color: pink;
}
</style>
Html和JavaScript部分:
<body>
<button id="btn">获取宽度</button>
<div class="box" id="box">box</div>
<script>
var btn=document.getElementById('btn');
var box=document.getElementById('box');
btn.onclick=function(){
console.log(getComputedStyle(box));
console.log(getComputedStyle(box)[348]);
con