div.switch-box input[type="checkbox"] {
display: none;
}
div.switch-box label.lab-switch {
position: relative;
height: 24px;
margin: 0;
vertical-align: middle;
cursor: pointer;
}
div.switch-box input[type="checkbox"]:checked+label.lab-switch::before {
background-color: #7ED321;
}
div.switch-box label.lab-switch::before {
display: inline-block;
content: '';
width: 45px;
height: 24px;
background-color: #D8D8D8;
border-radius: 100px;
transition: background-color 0.3s ease-in;
}
div.switch-box input[type="checkbox"]:checked+label.lab-switch::after {
-webkit-transform: translateX(130%);
transform: translateX(130%);
}
div.switch-box label.lab-switch::after {
position: absolute;
left: 4px;
top: 4px;
content: '';
width: 16px;
height: 16px;
border-radius: 50%;
background-color: #fff;
transition: -webkit-transform 0.3s ease-in;
transition: transform 0.3s ease-in;
transition: transform 0.3s ease-in, -webkit-transform 0.3s ease-in;
}
<div class="switch-box">
<input type="checkbox" id="name">
<label class="lab-switch" for="name"></label>
</div>
//是否选中
$('#name').prop('checked')
效果如下:
第二种常见写法:
#toggle-button {
display: none;
}
.button-label {
position: relative;
display: inline-block;
width: 80px;
height: 30px;
background-color: #f7ca99;
box-shadow: #f7ca99 0px 0px 0px 2px;
border-radius: 5px;
overflow: hidden;
}
.circle {
position: absolute;
top: 0;
left: 0;
width: 40px;
height: 30px;
border-radius: 14%;
background-color: #fff;
}
.button-label .text {
line-height: 30px;
font-size: 15px;
text-shadow: 0 0 2px #ddd;
}
.on {
color: #fff;
display: none;
text-indent: 4px;
}
.off {
color: #fff;
display: inline-block;
text-indent: 44px;
}
.button-label .circle {
left: 0;
transition: all 0.3s;
}
#toggle-button:checked+label.button-label .circle {
left: 40px;
}
#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: #82e497;
box-shadow: #82e497 0px 0px 0px 2px;
}
<div class="switch">
<input type="checkbox" id="toggle-button">
<label for="toggle-button" class="button-label">
<span class="circle"></span>
<span class="text on">显示</span>
<span class="text off">隐藏</span>
</label>
</div>
$('#toggle-button').prop('checked')//如果为true,为显示;false则为隐藏
效果如下: