选择器
html部分
<div class="toggle-container">
<input type="checkbox" id="good" class="toggle">
<label for="good" class="label">
<div class="ball"></div>
</label>
<span>good</span>
</div>
<div class="toggle-container">
<input type="checkbox" id="cheap" class="toggle">
<label for="cheap" class="label">
<div class="ball"></div>
</label>
<span>cheap</span>
</div>
<div class="toggle-container">
<input type="checkbox" id="fast" class="toggle">
<label for="fast" class="label">
<div class="ball"></div>
</label>
<span>fast</span>
</div>
css部分
*{
margin: 0;
padding: 0 ;
}
body{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
overflow: hidden;
}
.toggle-container{
display: flex;
align-items: center;
margin: 10px 0;
width: 200px;
}
.label{
position: relative;
background-color: #d0d0d0;
border-radius: 50px;
cursor: pointer;
display: inline-block;
margin: 0 15px 0;
width: 80px;
height: 40px;
}
.toggle{
visibility: hidden;
}
.toggle:checked + .label{
background-color: #8e44ad;
}
.ball{
background-color: #fff;
height: 34px;
width: 34px;
border-radius: 50%;
position: absolute;
top: 3px;
left: 3px;
animation: scrollOff .3s linear forwards;
}
.toggle:checked + .label .ball{
animation: scrollOn .3s linear forwards;
}
@keyframes scrollOff{
100%{
transform: translateX(0) scale(1);
}
50%{
transform: translateX(20px) scale(1.2);
}
0%{
transform: translateX(40px) scale(1);
}
}
@keyframes scrollOn {
50%{
transform: translateX(20px) scale(1.2);
}
100%{
transform: translateX(40px) scale(1);
}
}
js部分
// 获取dom
let toggles=document.querySelectorAll(".toggle")
toggles=Array.from(toggles)
// 按钮绑定事件
toggles.forEach((item)=>{
item.addEventListener("change",(e)=>{
const {checked,id}=e.target
if(all()){
if(id=='good'){
toggles[1].checked=false
}
if(id=='cheap'){
toggles[2].checked=false
}
if(id=='fast'){
toggles[0].checked=false
}
}
})
})
// 是否全选
function all(){
return toggles.every((item)=>{
return item.checked
})
}