在 jQuery 中,修改和获取 CSS 样式只需要一个 .css 就可以搞定了。实际内部也是通过 DOM 操作实现。设置 CSS 样式实际就是设定 DOM 的 style 属性,我们可以根据当前 DOM 元素的 style 属性获取其 CSS 样式,也可以修改或追加新的样式。

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>js lesson</title>
</head>
<body>
<h2 style="width:300px;height:200px;background-color:lightgreen;">DOM 操作</h2>
<input type="button" value="获取CSS" onclick="getCSS()">
<input type="button" value="设置CSS" onclick="setCSS()">
</body>
</html>
<script type="text/javascript">
var hh = document.getElementsByTagName("h2")[0];
function getCSS() {
// 只能获取行内样式
console.log(hh.style.width);
console.log(hh.style.height);
console.log(hh.style.backgroundColor);
}
function setCSS() {
// 可以新增原来没有的行内样式
hh.style.width = "auto";
hh.style.backgroundColor = "#CCC";
hh.style.color = "#FFF";
}
</script>