天天看點

checkbox、radio設定自定義樣式

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

1 <!DOCTYPE html>
 2 <html >
 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實作同上,效果圖如下:

checkbox、radio設定自定義樣式

轉載于:https://www.cnblogs.com/gerry2019/p/10677207.html