<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>案例031</title>
<style>
#box1{
width: 200px;
height: 200px;
background-color: rgb(162, 0, 255);
}
</style>
<script>
window.onload = function(){
var btn01 = document.getElementById("btn01");
var box1 = document.getElementById("box1");
btn01.onclick = function(){
box1.style.width = "300px";
box1.style.height = "300px";
box1.style.backgroundColor = "yellow";
}
var btn02 = document.getElementById("btn02");
btn02.onclick = function(){
console.log(box1.style.width);
console.log(box1.style.height);
console.log(box1.style.backgroundColor);
}
}
</script>
</head>
<body>
<button id="btn01">设置元素的样式</button>
<button id="btn02">获取元素的样式</button>
<br></br>
<div id="box1"></div>
</body>
</html>
我们现在获取元素样式以及设置元素样式都可以通过style属性获取,如果要设置样式的话,元素.style.属性 = "属性值",如果是获取样式的话,就是这样元素.style.属性,具体的实例就是上面代码。
其中注意的是,样式中写了!important,则此时样式会有最高的优先级,即使通过JS也不能覆盖该样式,此时将会导致JS修改样式失效,所以尽量不要为样式添加!important。style样式只能获取内联样式,不能获取在CSS选择器里面的。因为JavaScript通过style设置的样式是内联样式。