button实现switch开关按钮

涉及知识点

介绍

css实现switch开关按钮。
请添加图片描述

代码

HTML:

 <button class="switch">
     <span class="switch_circle circle_left"></span>
 </button>
 <button class="switch">
     <span class="switch_circle circle_left"></span>
 </button>

CSS:

 .switch{
    
    
     position: relative;
     box-sizing: content-box;
     width: 70px;
     height: 35px;
     padding: 0;
     border-radius: 40px;
     border:3px solid transparent;
 }
 .switch_active{
    
    
     background-color: #0052d9;
 }
 .switch_circle{
    
    
     position: absolute;
     top: 0;
     width: 35px;
     height: 35px;
     background-color:#fff;
     border-radius: 50%;
     transition: .5s;
 }
 .circle_left{
    
    
     left: 0;
 }
 .circle_right{
    
    
     left: 35px;
 }

JavaScript:

const switchs = document.getElementsByClassName("switch")

Array.from(switchs).forEach(ele => {
    
    
    let circle = ele.getElementsByClassName("switch_circle")[0]
    ele.addEventListener("click",()=>{
    
    
        ele.classList.toggle("switch_active")
        circle.classList.toggle("circle_left")
        circle.classList.toggle("circle_right")   
    })
});

猜你喜欢

转载自blog.csdn.net/qq_39706777/article/details/120290293