swith开关

每次写网页的时候差不多都要用到开关 我就想写一个需要的时候可以随时调用,能力有限代码比较繁琐,求各位大神简化下

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.switch{
50px;
height: 24px;
margin-bottom:10px ;
background: #18a063;
position: relative;
border-radius: 12px;
transition: all 1s;
}
.switch span{
position: absolute;
20px;
height: 20px;
border-radius: 10px;
left: 2px;
top: 2px;
background: #fff;
transition: all 1s;
}
</style>
</head>
<body>
<div class="switch" id="switch1">
<span></span>
</div>
<div class="switch" id="switch2">
<span></span>
</div>
<script type="text/javascript">
function Switch(id){
this.el = document.getElementById(id);
this.flag = true;
this.toggle();
}
Switch.prototype = {
toggle(){
this.el.onclick = ()=>{
if(this.flag){
this.el.style.background = "#999";
this.el.children[0].style.left = "28px"
this.flag = false;
}else{
this.el.style.background = "#18a063";
this.el.children[0].style.left = "2px"
this.flag = true;
}
}
}
}
let s1 = new Switch("switch1");
let s2 = new Switch("switch2");
</script>
</body>
</html>

效果图

原文地址:https://www.cnblogs.com/leitongtong/p/13878752.html