dom方式操作css
h5 API(classList)方式
css om方式
<html>
<head>
<style>
.white{
height:30px;
width:100px;
background-color:#fff;
border:red 1px solid;
}
.black{
height:30px;
width:100px;
background-color:#000;
border:red 1px solid;
}
</style>
</head>
<body>
<div>dom方式</div>
<div id='div1' style="height:30px;width:100px;background-color:#fff;border:red 1px solid;" onclick="dom(this);"></div>
<div>优点:操作简单,控制粒度细化,可以控制css的某个具体属性</div>
<div>dom-setAttribute方式</div>
<div id='div1' style="height:30px;width:100px;background-color:#fff;border:red 1px solid;" onclick="domSetAttribute(this);"></div>
<div>h5 API(classList)方式</div>
<div id='div2' class="white" onclick="api(this);"></div>
<div>优点:可以在类的范围改变元素的样式,可以实现在多个复杂样式间快速切换</div>
<div>css om方式</div>
<div id='div3' class="white" onclick="cssom(this);"></div>
<div>优点:没发现什么优点,但是与dom对象分离了,操作的是css对象</div>
<script>
function dom(elm){
elm.style.backgroundColor = "#000";
}
function domSetAttribute(elm){
elm.setAttribute('style', 'height:30px;width:100px;border:red 1px solid;background-color:darkblue;');
}
function api(elm){
elm.classList.remove('white');
elm.classList.add('black');
}
function cssom(elm){
let stylesheet = document.styleSheets[0];
stylesheet.cssRules[0].style.backgroundColor="blue";
}
</script>
</body>
</html>