JS中使用DOM操作css:
元素.style.样式名=样式值
注:如果css样式中含有-,这样名称在JS中是不合法的,需要将这种样式名修改为驼峰命名法。
获取元素显示的样式:
1.
元素.currentStyle.样式名 //只能读取不能修改
注:currentStyle只有IE浏览器支持
2.
getComputedStyle() //也是只能读取不能修改,并且需要两个参数,第一个:要获取样式的元素,第二个:可以传递一个伪元素,一般都传null,该方法会返回一个对象,对象中封装了当前元素对应的样式。
比如:getComputedStyle(box1,null).width;
注:此方法IE8以下的浏览器不支持
以上两种获取样式的方法有区别,如果获取的样式没有设置,getComputedStyle()则会获取到真实的值, currentStyle则会获取默认值(auto)。
以下是兼容所有浏览器的获取样式的函数:
function getstyle(obj,name){
if(window.getComputedStyle){
return getComputedStyle(obj,null)[name];
}else{
return obj.currentStyle[name];
}
}
也可以这样写:
function getstyle(obj,name){
return window.getComputedStyle?getComputedStyle(obj,null)[name]:obj.currentStyle[name];
}
还可以这样写:
function getstyle(obj,name) {
if(obj.currentStyle){
return obj.currentStyle[name];
}else{
return getComputedStyle(obj,null)[name];
}
} //这样写有一个问题,就是在IE8以上的IE浏览器中本来两种方法都有,这样写永远用的就是currentStyle这个方法,最好还是推荐用getComputedStyle方法。