<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>classList</title>
<style type="text/css">
.box{
width: 100px;
height: 100px;
margin: 10px 0;
background-color: blue;
}
.red{
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="box"></div>
<script type="text/javascript">
      /*classList:获取class列表属性
        length class的长度
        add() 添加class方法
        remove() 删除class方法
        toggle() 切换class方法
      */
var box = document.querySelectorAll('.box');
/*for (var i = 0; i < box.length; i++) {
box[i].isChecked = false;
box[i].onclick = function () {
if (this.isChecked) {
this.className = 'box';
} else {
this.className = 'box red';
}
this.isChecked = !this.isChecked;
}
}*/
/*for (var i = 0; i < box.length; i++) {
box[i].isChecked = false;
box[i].onclick = function () {
console.dir(this);
if (this.isChecked) {
this.classList.remove('red');
} else {
this.classList.add('red');
}
this.isChecked = !this.isChecked;
}
}*/
// 三目写法
for (var i = 0; i < box.length; i++) {
box[i].isChecked = false;
box[i].onclick = function () {
console.dir(this);
/*if (this.isChecked) {
this.classList.remove('red');
} else {
this.classList.add('red');
}*/
// this.isChecked ? this.classList.remove('red') : this.classList.add('red');
this.classList[this.isChecked?'remove':'add']('red');
this.isChecked = !this.isChecked;
}
}
</script>
</body>
</html>
04-30 03:03