javascript ES6 class类 使用示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.boxs {
display: flex;
justify-content: space-around;
align-items: center;
width: 400px;
color: white;
}
.box {
width: 20%;
height: 50px;
background: gray;
}
.active {
color: #00b7ee;
}
</style>
</head>
<body>
<div class="boxs">
<div class="box">高</div>
<div class="box">富</div>
<div class="box">帅</div>
</div>
</body>
</html>
<script>
class Client {
constructor (nodes) {
this.nodes = [...nodes];
this.initEvent();
}
initEvent () {
this.nodes.forEach(item => {
item.addEventListener('click', (e) => {
this.handleClick(e.target);
});
});
}
handleClick (ele) {
const items = this.nodes.filter(item => {
return item.classList.contains('active');
});
if (items.length === 2 && !items.includes(ele)) {
return;
}
ele.classList.toggle('active');
}
}
const client = new Client(document.querySelectorAll('.box'));
</script>