使用原生css3實現滑塊式開關按鈕
阿新 • • 發佈:2021-02-13
html程式碼如下:
<div class="switch-box"> <input type="checkbox" id="switch" hidden="hidden"> <label for="switch" class="switch"> <div class="dot"> </div> </label> </div>
css程式碼如下:
<style>
.switch-box{
width: 300px;
height: 300px;
margin: 100px auto;
}
.switch{
display: flex;
align-items: center;
width: 300px;
height: 80px;
background-color: #ccc;
border-radius : 50px;
transition: all 1s;
}
.dot{
width: 70px;
height: 70px;
background-color: #fff;
border-radius: 50%;
transform: translate(10px);
transition: all 1s;
}
#switch:checked ~.switch{
background-color : rgb(143, 189, 216);
}
#switch:checked ~.switch .dot{
transform: translate(220px);
background-color: rgb(48, 196, 241);
}
</style>
關鍵點是:將input標籤隱藏,採用label標籤與input建立聯絡。css3的關鍵點是偽類狀態選擇器和兄弟選擇器的使用。