JS的DOM操作css
通过JS修改元素的样式:
获取内联样式
- 语法:元素.style.样式名 = 样式值
- 注意:如果CSS的样式命名中含有 - ,比如: background-color 。需要去掉- ,使用驼峰命名法。改为: backgroundColor 。
给定一个200px的红色盒子box1、点击按钮1修改box1大小,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box1 {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div id="box1"></div>
<input type="button" id="btn1" value="按钮"/>
<input type="button" id="btn2" value="按钮"/>
</body>
</html>
<script type="text/javascript">
window.onclick = function () {
var box1 = document.getElementById("box1");
var btn1 = document.getElementById("btn1");
btn1.onclick = function() {
box1.style.width = "100px";
box1.style.height = "100px";
}
}
</script>
-
通过style属性设置的样式都是内联样式,而内联样式有较高的优先级,所以通过JS修改样式通常会立即显示。
-
但是在样式中写了 !important ,则此样式会有最高的优先级,即使通过JS也不能覆盖该样式,所以尽量不要为样式添加 !important 。
点击按钮2读取样式信息
var btn2 = document.getElementById("btn2");
btn2.onclick = function () {
alert(box1.style.backgroundColor);
console.log(box1.style.backgroundColor);
}
注意:当没有对元素进行内联样式修改前,直接读取的数据为空白。所以 元素.style.样式名 也只能读取内联样式。
获取元素当前的显示样式
- 语法:元素.currentStyle.样式名(只有IE浏览器支持,其他浏览器都不支持)
var btn2 = document.getElementById("btn2");
btn2.onclick = function () {
alert(box1.currentStyle.backgroundColor);
}
- 其他浏览器中可以使用 **getComputedStyle()**这个方法来获取。需要两个参数,第一个是要获取的元素,第二个是传递一个伪元素(一般传null),不支持IE8及以下。
var btn2 = document.getElementById("btn2");
btn2.onclick = function () {
alert(getComputedStyle(box1, null));
}
该方法返回的是一个对象。如果要获取对应元素可以在获取的对象后加 .样式名。如:getComputedStyle(box1, null).backgroundColor
-
编写一个getStyle函数使得浏览器能通用获取样式。
function getStyle(obj, name) { if(window.getComputedStyle) { //正常浏览器的方式,具有getComputedStyle()方法 return getComputedStyle(obj, null)[name]; }else { //IE8的方式,没有getComputedStyle()方法 return obj.currentStyle[name]; } //简写 //return window.getComputedStyle?getComputedStyle(obj, null)[name]:obj.currentStyle[name]; }