上一篇在我的博客中提到设置和读取css样式,都是内联样式。但在实际操作中我们确很少写内联样式,所以读取一个元素的样式就会用到另一个方法。
获取元素的当前样式,当前显示的样式。
1、语法:object.currentstyle.style name
适用于IE8及以下的游览器。
例:object.currentstyle.style name
<html>
<head>
<style>
#box{width:100px;
height:100px;
background-color:red;
}
</style>
<script>
window.onload = function(){
var box = document.getElementByID(" box");
var btn =document.getElementByID("btn");
btn.onclick =function(){
alert(box.currentstyle.width);
//显示出box的CSS样式。
}
};
</script>
</head>
<body>
<div id =" box"></div>
<button id = "btn">点击按钮<button>
</body>
</html>
2、语法:getcomputedstyle(objet,null)
适用于IE8以上的游览器和其它浏览器。
例:getcomputedstyle(objet,null)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style type="text/css">
#box{width: 100px;
height: 100px;
background-color: aqua;}
</style>
<script>
window.onload = function(){
var box = document.getElementById("box");
var btn = document.getElementById("btn");
btn.onclick= function(){
alert(getComputedStyle(box,null).width);
};
};
</script>
</head>
<body>
<div id="box"></div>
<button id="btn">点击一下</button>
</body>
</html>
该方法会返回一个对象,对象中封装了当前元素对应的样式
通过object.style name 来读取样式。
这个无法修改样式,只能读取。
如果样式没有设置,不会读取默认值,会读取到当前真实的style value
3、通过定义一个函数,用来获取指定元素的当前样式。
getstyle 解决游览器兼容的问题:
<script>
window.onload = function(){
var box = document.getElementById("box");
var btn = document.getElementById("btn");
btn.onclick= function(){
var ws = getstyle(box,"width");
alert(ws);
};
function getstyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{
return obj.currentSytle.name
};
};
};
</script>
上面的if条件语句可以写成三目运算,
window.getcomputedstyle?getComputedStyle(obj,null)[name]:obj.currentSytle.name
? 是三目运算符,也叫条件运算符。