JS获取当前有效样式
方法一
【注】通过这种方式,只能找到行间的css样式
<!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>
#div1{background-color: blue;}
.box{height: 300px;}
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById("div1");
var oDiv2 = document.getElementById ("div2");
alert(oDiv.style.backgroundColor);
alert(oDiv2.style.backgroundColor);
}
</script>
</head>
<body>
<div id = 'div1' style = 'width: 200px; background-color: red;' class = 'box'></div>
<div id = "div2"></div>
</body>
</html>
运行结果:
方法二
获取当前的有效样式
系统提供了两个方法(不同的浏览器);
<!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>
#div1{background-color: blue;}
.box{height: 300px;}
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById("div1");
alert(oDiv2.style.backgroundColor);
//alert(oDiv.currentStyle['height']);//IE
//alert(getComputedStyle(oDiv)["height"]);//火狐,谷歌
alert(getStyle(oDiv,"background-color"));
}
//跨浏览器的兼容
function getStyle(node,cssStyle){
return node.currentStyle ? node.currentStyle[cssStyle] : getComputedStyle(node)[cssStyle];
}
</script>
</head>
<body>
<div id = 'div1' style = 'width: 200px; background-color: red;' class = 'box'></div>
</body>
</html>
运行结果: