background
When I was working on the project yesterday, I met a small problem. It's about switch button. That's it We have seen it in many places. The most typical is the notification management of our mobile phone. We often receive notifications from various apps. It's annoying, isn't it? There's a "allow notifications" button, just disable it. How does it work?
The implementation of switchButton
An input element with type = checkbox, a label element, a block level element div that wraps them, and a prototype of switch will come out. It's like this
<div class="switch mt5 switch-primary round switch-inline"> <input type="checkbox" name="itemSwitch" id="itemSwitch"> <label for="itemSwitch"></label> </div>
The style is:
.switch { position: relative; display: inline-block; width: 60px; height: 34px; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } input { display: none; }
summary
The process of making switchButton is as follows:
- Template: div{input[checkbox] + label} = switchButton
- css: set the width and height of the outermost layer and the positioning method as relative positioning, set the absolute positioning matting for sub elements, hide the div, and set whether the elements inside are the checked background color. When setting the checked element, move the entire label distance on the x position. If the switchbutton is a fillet, set border radius as well.
Note: if you want to disable the click event of the checkbox, you only need to add disabled directly in the input.