使用JavaScript获取和修改CSS
1、行内元素样式
-
获取值:obj.style.属性名
-
设置值:obj.style.属性名 = 属性值;
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id='div1' style="color: red;"></div>
<script type="text/javascript">
var obj = document.getElementById('div1') ;
console.log(obj.style.color); // red
obj.style.color = 'yellow';
console.log(obj.style.color); // yellow
</script>
</body>
</html>
2、 非行间样式元素
使用的方法为getComputedStyle()
此方法用于获取指定元素的 CSS 样式。
获取的样式是元素在浏览器中最终渲染效果的样式。
语法
window.getComputedStyle(element, pseudoElement)
参数说明:
> element: 必需,要获取样式的元素。
>pseudoElement: 可选,伪类元素,当不查询伪类元素的时候可以忽略或者传入null。
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js获取内部部样式</title>
<style>
#div{
width: 200px;
height: 200px;
border:3px solid cyan;
}
</style>
</head>
<body>
<div id="div""></div>
</body>
<script>
var div = document.getElementById('div');
//获取div的width
var width = window.getComputedStyle(div,null).width;
alert(width);//200px
//修改div的width
div.style.cssText='width:300px;'
</script>
</html>
3、兼容各种浏览器js获取css样式写法
原理:obj.currentStyle():兼容各版本IE,但不兼容火狐、谷歌
window.getComputedStyle():兼容火狐、谷歌,但不兼容IE;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
#div1 {
width: 500px;
}
</style>
</head>
<body>
<div id='div1' style="color: red;"></div>
<script type="text/javascript">
/*
* 参数列表:
* ele:DOM对象
* prop:属性名
* val:属性值
*/
function getAndSetStyle(ele, prop, val) {
if(val) {
// 设置值
ele.style[prop] = val;
}else {
// 兼容ie8以下
if(ele.currentStyle) {
return ele.currentStyle[prop];
}else {
return window.getComputedStyle(obj)[prop];
}
}
}
var obj = document.getElementById("div1");
console.log(getAndSetStyle(obj, 'color')); // red
console.log(getAndSetStyle(obj, 'width')); // 500px
getAndSetStyle(obj, 'height', '200px');
console.log(getAndSetStyle(obj, 'height')); // 200px
</script>
</body>
</html>