加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
strategy.html 2.20 KB
一键复制 编辑 原始数据 按行查看 历史
doudoucode 提交于 2020-06-29 17:38 . doudou init commit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.boxs{
display: flex;
flex-direction: row;
}
.box{
margin: 20px;
width:100px;
height:100px;
background: #999;
text-align: center;
font-size: 2rem;
line-height: 100px;
transition: all 0.5s ease-in-out;
user-select: none;
cursor: pointer;
border-radius: 100%;
box-shadow: 2px 5px 60px #ddd;
}
.active{background:red}
</style>
<body>
<div class="boxs">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<script>
class Client{
constructor(nodes,strategy){
this.nodes = [...nodes];
this.strategy = strategy;
this.initEvent();
}
initEvent(){
this.nodes.forEach(item=>{
item.addEventListener("click",(e)=>{
this.handleClick(e.target);
})
})
}
handleClick(ele){
this.strategy.process(ele,this.nodes);
}
}
class Strategy1{
process(ele,nodes){
ele.classList.toggle("active");
}
}
class Strategy2{
process(ele,nodes){
const items = nodes.filter(item=>item.classList.contains("active"));
if(items.length===2 && !items.includes(ele))
return;
ele.classList.toggle("active");
}
}
class Strategy3{
process(ele,nodes){
ele.classList.toggle("active");
if(nodes.every(item=>item.classList.contains("active"))){
nodes.filter(item=>item!==ele)[Math.floor(Math.random()*2)]
.classList.toggle("active");
}
}
}
const client = new Client(document.querySelectorAll(".box"),new Strategy3());
</script>
</body>
</html>
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化