注:style它只能獲取到內聯樣式中的屬性值;currentStyle它由於兼容性不好,是IE專屬的用來獲取CSS屬性,但是谷歌和火狐都不支持;getComputedStyle()方法,也不能完美兼容,只支持IE9+以上的瀏覽器
故,使用一個函數將其兼容性統一解決:
var CurrentStyle = function (element) {
return element.currentStyle || document.defaultView.getComputedStyle(element, null);
};
完整代碼可供參考如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>讀取元素當前樣式</title>
<style>
#box1 {
width: 200px;
height: 200px;
background-color: yellow;
}
</style>
<script type="text/javascript">
window.onload = function () {
var CurrentStyle = function (element) {
return element.currentStyle ||
document.defaultView.getComputedStyle(element, null);
};
var box1 = document.getElementById("box1");
var btn01 = document.getElementById("btn01");
btn01.onclick = function () {
alert(box1.style.width); //style只能讀內聯樣式
alert(CurrentStyle(box1).width); //基本樣式都可以讀出來
}
}
</script>
</head>
<body>
<button id="btn01">點擊1</button>
<br><br>
<div id="box1"></div>
</body>
</html>