<!DOCTYPE html> <html> <head > <meta charset="utf-8"> <title></title> <style type="text/css"> /* 使用: 1、html:修改input id和label for onclick="test1()" 2、css:修改#switch1:checked~label:before名字 修改#switch1:checked~label名字 3、js:函數名字 改按鈕大小 1、改switch-container的寬高 2、改label:before的寬為switch-container的寬 3、改#switch:checked~label:before的left為switch-container的寬 */ /* 開關的大小*/ .switch-container{ height: 24px; width:48px; } /*設置checkbox不顯示*/ .switch{ display: none; } /*設置label標簽為橢圓狀*/ .switch-container label{ display: block; background-color: #eee; height: 100%; width: 100%; cursor: pointer; border-radius: 25px; position: relative; } /*在label標簽內容之前添加如下樣式,形成一個未選中狀態*/ .switch-container label:before { content: ''; display: block; border-radius: 25px; height: 100%; width: 24px; background-color: white; position: absolute; left: 0px; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.08); -webkit-transition: all 0.5s ease; transition: all 0.5s ease; } /*選中后,未選中樣式消失*/ #switch:checked~label:before { left: 24px; } /*選中后label的背景色改變*/ #switch:checked~label { background-color: #4dbd74; } /*選中后,未選中樣式消失*/ #switch1:checked~label:before { left: 24px; } /*選中后label的背景色改變*/ #switch1:checked~label { background-color: #4dbd74; } </style> </head> <body> <div class="switch-container "> <input type="checkbox" id="switch" class="switch"> <label for="switch" onclick="test()"></label> </div> <div class="switch-box" style="width: 100px;"> <div class="switch-container " style="float: left;"> <input type="checkbox" id="switch1" class="switch"> <label for="switch1" onclick="test1()"></label> </div> <div style="float: right;"> <span id="switch1Con">選中</span> </div> </div> <script> var test = function(){ console.log(!document.getElementById('switch').checked ? "選中" : "未選中"); } var test1 = function(){ if (!document.getElementById('switch1').checked ) { document.getElementById('switch1Con').innerHTML="開啟"; }else{ document.getElementById('switch1Con').innerHTML="開啟"; } } </script> </body> </html>