一、操作css内联(只能操作内联样式)样式
格式:对象.style.样式名
例如:
var box1=document.getElementById(“box1”);
box1.style.backgroundColor=’#ccc’;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box1{
height: 200px;
width: 200px;
background-color: #a8f;
}
</style>
<script type="text/javascript">
/**
* style只能读取和数字内联样式
*/
window.onload=function(){
var btn1=document.getElementById("btn1");
var box1=document.getElementById("box1");
btn1.onclick=function(){
box1.style.backgroundColor='#ccc';
box1.style.color='orangered';
box1.style.height="300px";
}
};
</script>
</head>
<body>
<div id="box1">
box1
<button id="btn1">改变背景颜色</button>
</div>
</body>
</html>
二、获取当前样式(无法设置,如果需要设值,可以使用style)
IE8中支持 currentStyle
火狐和谷歌等浏览器不支持,可以使用window.getComputedStyle
所以考虑兼容性,封装如下
使用格式:对象.style.样式名
例如:
var box1=document.getElementById(“box1”);
getStyle(box1).backgroundColor;
function getStyle(obj) {
var style = null;
if(window.getComputedStyle) {
style = window.getComputedStyle(obj, null);
}else{
style = obj.currentStyle;
}
return style;
}