checkbox、radio設置自定義樣式

  老生常談,作一個簡單的記錄。瀏覽器自帶的checkbox和radio樣式可能不符合項目要求,一般要作一些自定義樣式設置,目前基本的解決思路都是將input[type=checkbox/radio]隱藏,用label去與input作聯動處理,具體實現方法有如下兩種:html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <style>
 9         /* 方法1 */
10         
11         label {
12             display: inline-block;
13             width: 15px;
14             height: 15px;
15             background: url('../../../assets/img/unchecked.svg') no-repeat 100% 100%;
16         }
17         
18         input[type="checkbox"]:checked+label {
19             background: url('../../../assets/img/checked.svg') no-repeat 100% 100%;
20         }
21         /* 方法2 */
22         
23         #test+span {
24             display: inline-block;
25             width: 15px;
26             height: 15px;
27             background: url('../../../assets/img/unchecked.svg') no-repeat 100% 100%;
28         }
29         
30         #test:checked+span {
31             background: url('../../../assets/img/checked.svg') no-repeat 100% 100%;
32         }
33     </style>
34     <title>checkboxAndRadio</title>
35 </head>
36 
37 <body ng-app="app">
38     <div>方法1</div>
39     <input type="checkbox" id="checkbox" style="display: none;">
40     <label for="checkbox"></label><br>
41     <div>方法2</div>
42     <input type="checkbox" id="test" style="display: none;">
43     <span></span>
44     <script>
45         document.getElementsByTagName('span')[0].addEventListener('click', function(e) {
46             this.previousElementSibling.checked = !this.previousElementSibling.checked;
47         })
48     </script>
49 </body>
50 
51 </html>

  第一種方式必需要設置元素id,若是表單過多將致使命名很糾結;第二種能夠簡單的寫一個事件監聽,去動態改變checkbox的選中狀態,以此來達到動態切換的目的。在利用框架進行開發應用時,只須要進行簡單的封裝便可使用,radio實現同上,效果圖以下:瀏覽器

相關文章
相關標籤/搜索