HTML
<input type="checkbox" name="switch2" id="switch2" class="choose-btn" data-toggle="开启|关闭"> <label for="switch2" class="choose-label"></label> <span class="choose-text"></span>
* 注意input的id和label的for必须一致
* 如果无需显示开关提示文字,则不需要choose-text
CSS
.choose-btn { display: none; } .choose-label { box-shadow: #b1b1b1 0px 0px 0px 1px; width: 30px; height: 16px; display: inline-block; border-radius: 16px; position: relative; background-color: #bdbdbd; overflow: hidden; margin: 0; margin-top: 4px; cursor: pointer;vertical-align: middle; } .choose-label:before { content: ‘‘; position: absolute; left: 0; width: 16px; height: 16px; display: inline-block; border-radius: 20px; background-color: #fff; z-index: 20; -webkit-transition: all 0.2s; transition: all 0.2s; } .choose-btn:checked + label.choose-label:before { left: 14px; } .choose-btn:checked + label.choose-label { background-color: #009cef; box-shadow: #009cef 0px 0px 0px 1px; }
JS(需要Jquery)如果无需显示开关提示文字,则不需要js
$(document).ready(function(){ $(".choose-btn").each(function(){ var texts = $(this).attr(‘data-toggle‘).split(‘|‘); $(this).siblings(‘.choose-text‘).text(this.checked?texts[0]:texts[1]); }); $(".choose-btn").on("change", function(){ var texts = $(this).attr(‘data-toggle‘).split(‘|‘); $(this).siblings(‘.choose-text‘).text(this.checked?texts[0]:texts[1]); }); });
效果:
原文地址:https://www.cnblogs.com/mankii/p/11090541.html
时间: 2024-11-14 12:50:58