你們好,我又來了,此次給你們表演使用純css實現開關效果css
咱們使用<input type="checkbox">標籤來實現這個效果。
checkbox的選中、未選中的特性,恰好對應開關的打開、關閉
on:打開 off:關閉cookie
<label for="ck2"> <input type="checkbox" id="ck2"> <span>未選中,則關閉開關</span> </label> <br> <label for="ck1"> <input type="checkbox" id="ck1" checked> <span>選中,則打開開關</span> </label>
這裏要講解一下,使用了position來實現的定位。有不瞭解的同窗能夠打開MDN查看相關知識優化
<P>off狀態草圖</P> <div class="toggle"> <div class="cookie"></div> </div> <br> <P>on狀態草圖</P> <div class="toggle2"> <div class="cookie2"></div> </div>
.toggle{ display:inline-block; position:relative; height:25px; width:50px; border-radius:4px; background:#CC0000; } .cookie{ position:absolute; left:2px; top:2px; bottom:2px; width:50%; background:rgba(230,230,230,0.9); border-radius:3px; } .toggle2{ display:inline-block; position:relative; height:25px; width:50px; padding:2px; border-radius:4px; background:#66CC33; } .cookie2{ position:absolute; right:2px; top:2px; bottom:2px; width:50%; background:rgba(230,230,230,0.9); border-radius:3px; }
<label for="ck4"> <input type="checkbox" id="ck4"> <div class="toggle"> <div class="cookie"></div> </div> </label> <br> <label for="ck3"> <input type="checkbox" id="ck3" checked> <div class="toggle2"> <div class="cookie2"></div> </div> </label>
<label for="ck5"> <input type="checkbox" id="ck5"> <div class="toggle-finish"> <div class="cookie-finish"></div> </div> </label> <br> <label for="ck6"> <input type="checkbox" id="ck6" checked> <div class="toggle-finish"> <div class="cookie-finish"></div> </div> </label>
.toggle-finish{ cursor:pointer; display:inline-block; position:relative; height:25px; width:50px; border-radius:4px; background:#CC0000; } .cookie-finish{ position:absolute; left:2px; top:2px; bottom:2px; width:50%; background:rgba(230,230,230,0.9); border-radius:3px; } input:checked + .toggle-finish{ background:#66CC33; } input:checked + .toggle-finish .cookie-finish{ left:auto; right:2px; }
到此爲止就已經基本實現一個開關的功能了,記得將input隱藏起來哦
能夠點擊預覽https://codepen.io/Ritr/pen/W...
另外我還優化了一個動畫版
https://codepen.io/Ritr/pen/L...動畫