有两种方法:
第一种:currentStyle
语法:元素.currentStyle.样式名
他可以用来读取当前元素正在显示的样式
如果当前元素没有设置该样式,则获取它的默认值
currentStyle只有在IE浏览器中支持,其他浏览器都不支持。
第二种:getComputedStyle()方法
getComputedStyle()这个方法来获取元素当前的样式
这个方法是window的方法,可以直接使用
需要两个参数
第一个:要获取样式的元素
第二个:可以传递一个伪元素,一般都传null
该方法会返回一个对象,对象中封装了当前元素对应的样式
可以通过 对象.样式名 来读取样式
如果没有设置样式则会获取到真实的值,而不是默认值
比如:没有设置width,它不会获取到auto,而是一个长度
该方法不支持IE8及以下浏览器
但是我们需要都兼容怎么办? 那我们就自己写一个方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1 {
width: 100px;
height: 100px;
background-color: #bfa;
}
</style>
<script>
window.onload = function() {
var box1 = document.getElementsByClassName("box1")[0];
var btn01 = document.getElementsByClassName("btn01")[0];
btn01.onclick = function() {
// alert(box1.currentStyle.width);
// var box = getComputedStyle(box1, null);
alert(getStyle(box1, "width"));
};
};
function getStyle(obj, name) {
if (window.getComputedStyle) {
return getComputedStyle(obj, null)[name];
} else {
return obj.currentStyle.width;
}
}
</script>
</head>
<body>
<button class="btn01">按钮</button>
<div class="box1">
</div>
</body>
</html>
把方法分离出来:
function getStyle(obj, name) {
if (window.getComputedStyle) {
return getComputedStyle(obj, null)[name];
} else {
return obj.currentStyle.width;
}
}
当调用该方法的时候,它会检查浏览器中是否有getComputedStyle,如果又我们会使用getComputedStyle,否则会使用currentStyle,这样就完美解决了,所有的浏览器都能兼容。
但是我们为什么要在getComputedStyle前加一个window呢?说明一下:
- 当不加window时,getComputedStyle 是作为一个变量来判断的,如果没有就会报错,结束下面的程序。
- 加上windon时,getComputedStyle是作为一个属性来判断了,如果没有返回underfind。执行else
**注意:通过currentStyle和getComputedStyle()读取到的样式都只是读的,不能修改,如果要修改可以通过修改style属性。**
愿你的坚持终有收获。