在写Js时,经常需要获取元素的属性,从而进行操作,下面讲解经常用到的几种方法,以及他们各自的有缺点:
总结来说:1.元素.style.属性名,仅用于内联样式
如果样式中含有“-”,是属于不合法的属性名,使用驼峰命名法,即去掉“-”,将后面的第一个字母大写。如background-color,应改成backgroundColor
2.元素.currentStyle.属性名,仅适用于IE浏览器
3.在其他浏览器中可以使用 getComputedStyle(),他是window的方法
需要两个参数:
第一个:样式的元素
第二个:传递一个伪元素,一般为null
该方法返回一个对象,封装了样式,可通过对象.样式名来读取样式
currentStyle与getComputedStyle()对比:
1.最大的不同就是他们的兼容浏览器不同:
currentStyle仅兼容IE,而getComputedStyle()兼容除IE9以下的IE版本,其他浏览器均支持
2.getComputedStyle()如果获取的样式没有设置,则会获取真实的值,而不是默认值,如没有设置width,他不会获取auto,而是当前长度。
而currentStyle在没有设置样式的情况则显示的是默认样式
其实如果不考虑IE的特殊性的话,明显getComputedStyle()会更好用一些
如果想要所有的浏览器均兼容的话,则可以采取自定义
var w=getStyle(box01,"backgroundColor");
alert(w);
function getStyle(obj,name){
if(window.getComputedStyle){
//正常浏览器的方法
return getComputedStyle(obj,null)[name];
}
else{
//IE8的方式,没有getComputedStyle的方式
return obj.currentStyle[name];
}
}
注意:window.getComputedStyle中的window,没有加则会报错。
不加window说明是变量,变量现在局部找,没照着再在去全局找。再没找找到则报错,而加window说明是属性,属性没找到,则是underfined
还有一个要注意,就是通过currentStyle和getComputedStyle()得到的属性都只是只读,不能重新写值
以下是全过程,script的位置也可放在最前面,但需要加onload,表示页面均加载完成,再操作js代码。推荐放后面,效率也高一点
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#box01{
width: 200px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<input type="button" id="btn" value="点我一下" />
<div id="box01" >
你好!
</div>
<script type="text/javascript">
var box01=document.getElementById("box01")
var btn=document.getElementById("btn");
btn.onclick=function(){
// box01.style.width="400px";
//box01.style.width仅能用于内联样式
// alert(box01.style.width);
/*
* box01.currentStyle.backgroundColor
* 仅支持IE浏览器
*/
//alert(box01.currentStyle.backgroundColor);
/*
* getComputedStyle(box01,null).backgroundColor
* 仅支持IE8以上的版本,谷歌火狐等其他浏览器均支持
*/
//alert(getComputedStyle(box01,null).backgroundColor);
/*
* 要想所有的浏览器均兼容,可采取自定义函数
*/
var w=getStyle(box01,"backgroundColor");
alert(w);
function getStyle(obj,name){
if(window.getComputedStyle){
//正常浏览器的方法
return getComputedStyle(obj,null)[name];
}
else{
//IE8的方式,没有getComputedStyle的方式
return obj.currentStyle[name];
}
}
}
</script>
</body>
</html>