HTML使用Radio Input來實現Tab切換
阿新 • • 發佈:2018-12-21
在開發中看見僅使用css技巧,就用HTML的Radio Input來實現的Tab的切換,連click事件都未使用。程式碼效果如下:
<!DOCTYPE HTML> <html> <header> <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css"> <style> input { display: none; } input:checked + label { color: #2d3538; border-top: 2px solid #148ac4; border-bottom: 1px solid #fff; background-color: white; } label:hover { cursor: pointer; background: #148ac4 ; } .label-tab { display: inline-block; width: 100px; padding: 0 10px 0 10px; text-align: center; background: #eee; border-top-left-radius: 5px; border-top-right-radius: 5px; } .fa { padding-right: 5px; } .tab-panel { visibility: hidden; position: absolute; width: 300px; height: 100px; border: 1px solid #333; } #admin-tab:checked ~ #admin-panel, #user-tab:checked ~ #user-panel { visibility: visible; } </style> </hearder> <body> <input id="admin-tab" type="radio" name="tab" value="admin" checked="true"/> <label for="admin-tab" class="label-tab"><i class="fa fa-users" aria-hidden="true"></i>管理員</label> <input id="user-tab" type="radio" name="tab" value="user" /> <label for="user-tab" class="label-tab"><i class="fa fa-user" aria-hidden="true"></i>普通使用者</label> <div id="admin-panel" class="tab-panel"> 我是管理員 </div> <div id="user-panel" class="tab-panel"> 我是普通使用者 </div> </body> </html>
1. label的for屬性要和對於的input的id值保持一致,點選label時才能相當於點選了對應的radio button。
2. 使用#admin-tab:checked ~ #admin-panel之類樣式來設定對應的panel是否顯示。
3. 使用input:checked + label來設定label選中後的樣式效果。
4. 使用label:hover來設定滑鼠在label上的樣式效果。
5. 圖示使用了流行的font-awesome,<i class="fa fa-users" aria-hidden="true"></i>即對應相應的圖示。
6. label的display需要設定成塊級顯示,否則width樣式不起作用。