1、读写元素css属性
dom.style.prop //只有这个可以写入
- 可以读写行间样式,没有兼容性问题,碰到float这样的保留字属性,前面应该加css。eg:float->cssFloat
- 复合属性必须拆解,组合单词变成小驼峰式写法 background-color ->backgroundColor
- 写入的值必须是字符串格式
2、查询计算样式
window.getComputedStyle(ele,null)
- 获取的是 当前元素的所有css展示值 包括默认值 ,null可以获取伪元素
- 计算样式只读
- 返回的计算样式的值都是绝对值,没有相对单位
- IE8及以下不兼容(dom.currentStyle
只能获取,不能修改,返回的计算样式的值不是经过转换的绝对值,IE独有属性)
3、获取伪元素的样式表
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<link rel="stylesheet" href="./src/demo.css">
<style type="text/css">
div{
width:100px;
height: 100px;
background-color: red;
}
.active{
width:200px;
height: 200px;
background-color: green;
}
/*div::after{
content: "";
width:50px;
height: 50px;
background-color: green;
display: inline-block;
}
</style>
</head>
<body>
<script type = "text/javascript>
//点击这个div点击一次就会变成宽200高200背景颜色为green的
var div = document.getElementsByTagName('div')[0];
div.onclick = function(){
// div.style.width = "200px";
// div.style.height = "200px";
// div.style.backgroundColor = "red";
div.className = "active";
}
</script>
</body>
</html>
4、让方块运动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<link rel="stylesheet" href="./src/demo.css">
<style type="text/css">
</style>
</head>
<body>
<div style="width:100px;height: 100px;background-color: red;position: absolute;left: 0;top: 0;"></div>
<script type="text/javascript">
function getStyle(elem,prop){
if(window.getComputedStyle){
return window.getComputedStyle(elem,null)[prop];
}else{
return elem.currentStyle[prop];
}
}
var div = document.getElementsByTagName('div')[0];
// 让方块移动
var timer= setInterval(function(){
div.style.left = parseInt(getStyle(div,'left')) + 10 +'px'; //
if(parseInt(div.s每次移动之前都要知道方块当前的位置和我们想让他移动的距离tyle.width) > 1000) {
clearInterval(timer); //停止运动
}
},100);
</script>
</body>
</html>