<!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=" 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>