效果圖預覽:
完整代碼如下:
<!DOCTYPE html>
<html>
<head>
<title>純css編寫開關按鈕點擊切換</title>
<style type="text/css">
#toggle-button{
display: none;
}
.button-label{
position: relative;
display: inline-block;
width: 80px;
background-color: #ccc;
border: 1px solid #ccc;
border-radius: 30px;
cursor: pointer;
}
.circle{
position: absolute;
top: 0;
left: 0;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #fff;
}
.button-label .text {
line-height: 30px;
font-size: 18px;
/*
用來阻止頁面文字被選中,出現藍色
可以將下面兩行代碼註釋掉來查看區別
*/
-webkit-user-select: none;
user-select: none;
}
.on {
color: #fff;
display: none;
text-indent: 10px;
}
.off {
color: #fff;
display: inline-block;
text-indent: 53px;
}
.button-label .circle{
left: 0;
transition: all 0.3s;/*transition過度,時間為0.3秒*/
}
/*
以下是checked被選中後,緊跟checked標籤後面label的樣式。
例如:div+p 選擇所有緊接着<div>元素之後的<p>元素
*/
#toggle-button:checked + label.button-label .circle{
left: 50px;
}
#toggle-button:checked + label.button-label .on{
display: inline-block;
}
#toggle-button:checked + label.button-label .off{
display: none;
}
#toggle-button:checked + label.button-label{
background-color: #33FF66;
}
</style>
</head>
<body>
<input type="checkbox" id="toggle-button">
<!--label中的for跟input的id綁定。作用是在點擊label時選中input或者取消選中input-->
<label for="toggle-button" class="button-label">
<span class="circle"></span>
<span class="text on">開</span>
<span class="text off">關</span>
</label>
</body>
</html>
知識點:
1. label中的for跟input的id綁定。作用是在點擊label時選中input或者取消選中input
2. (:checked + 緊鄰其後面標籤) 的選擇器。例如:#toggle-button:checked + label 解釋:當id為toggle-button的checked為選中狀態時,就選擇緊鄰其後的label標籤
3. user-select: none;這個屬性用來阻止頁面文字被選中,如果不添加此屬性,點擊切換開關時,開/關 二字有時候會被選中,出現藍色背景,如下圖: