在js中获取css样式的方法
一、使用currentStyle
使用方法为 currentStyle . 样式名
例如
alert(box.currentStyle.height);
但是该方法有一个缺陷只能在IE中使用
二、使用getComputedStyle
使用方法为 getComputedStyle( , )
getComputedStyle( , )里面有两个值第一个为所获取的元素,第二个一般为空
var obj = document.getElementById("obj");
getComputedStyle(obj,null);
获取其中具体样式方法
var obj = getComputedStyle(obj,null)
alert(obj.width);
但是这种方法也有局限它不支持IE8及以下的浏览器
因此可以采用一个更为兼容的方法
三、创建一个getStyle()函数
function getStyle(obj,name){
if(window.getComputedStyle){ //判断浏览器
return getComputedStyle(obj,null)[name];
}
else{
return box.currentStyle[name];
}
}
还有一种写法与上面的效果一样 但是逼格更高
function getStyle(obj,name){
return window.getComputedStyle?getComputedStyle(box,null)[name]:box.currentStyle[name];
}
下面是整体源代码,了解一下HTML和css部分和整体的效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box{
width: auto;
height: 100px;
background-color: aqua;
}
</style>
<script type="text/javascript">
window.onload = function(){
var box = document.getElementById("box");
var btn = document.getElementById("btn");
btn.onclick = function(){
// alert(box.currentStyle.height); //仅限IE
// var obj = getComputedStyle(box,null);
// alert(obj.width);//不支持IE8及以下的浏览器
alert(getStyle(box,"width"));
}
function getStyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}
else{
return box.currentStyle[name];
}
}
function getStyle(obj,name){
return window.getComputedStyle?getComputedStyle(box,null)[name]:box.currentStyle[name];
}
}
</script>
</head>
<body>
<div id="box"></div>
<button type="button" id="btn">点击</button>
</body>
</html>