首先是構思
我們使用<input type="checkbox">
標簽來實現這個效果。
checkbox的選中、未選中的特性,剛好對應開關的打開、關閉
on:打開 off:關閉
<label for="ck2"> <input type="checkbox" id="ck2"> <span>未選中,則關閉開關</span></label><br><label for="ck1"> <input type="checkbox" id="ck1" checked> <span>選中,則打開開關</span></label>
開始畫出off、on狀態的草圖
這里要講解一下,使用了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內
<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和checkbox整理、優化css
<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...
總結
以上所述是小編給大家介紹的使用純css實現開關效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
新聞熱點
疑難解答