通过document.getElementById( element ).style.xxx可以获取元素的样式信息,但是对于通过clss属性引用的外部样式表就获取不到了,如下面的例子:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#square{
width: 150px;
height: 150px;
background: red;
}
</style>
</head>
<body>
<div id="square"></div>
<div id="circle" style="width: 150px;height: 150px;background: blue;"></div>
<script>
var square = document.getElementById("square").style.width;
console.log(square); //空值
var circle = document.getElementById("circle").style.width;
console.log(circle); //150px
</script>
</body>
</html>
也就是说用document.getElementById( element ).style.xxx 获取的知识DOM元素style属性里的样式规则,对于通过class属性引用的外部样式表,就拿不到我们要的信息了。
解决办法
使用DOM标准里的全局方法getComputedStyle,可以获取当前对象样式规则信息,如: getComputenStyle(obj,null).paddingLeft,就能获取对象的左内边距。但是可悲的是IE不支持此方法,IE有自己的实现方法,那就是currentStyle,不同于getComputedStyle,currentStyle是作为DOM属性存在的,如:obj.currentStyle.paddingLeft,在IE中就获取到对象的左内边距了,兼容性的写法如下:
return window.getComputedStyle ? window.getComputedStyle(obj,null).paddingLeft : obj.currentStyle.paddingLeft;
用js的style属性可以获得html标签的样式,但是不能获取非行间样式。那么怎么用js获取css的非行间样式呢?在IE下可以用currentStyle,而在火狐下面我们需要用到getComputedStyle。下面是一个小示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#content{
width: 100px;
height: 100px;
background: pink;
}
</style>
</head>
<body>
<div id="content"></div>
<script>
function getStyle(ele,attr){
if(ele.currentStyle){
return ele.currentStyle[attr];
}else{
return getComputedStyle(ele,null)[attr];
}
}
window.onload = function(){
var content = document.getElementById("content");
console.log(getStyle(content,"width")); //100px
}
</script>
</body>
</html>
1万+

被折叠的 条评论
为什么被折叠?



