使用表單驗證時,CheckBox 是不可缺少的一部分。
由於瀏覽器兼容性,checkbox 會顯示不同的樣式,直接設置 input 的 backgroundColor 屬性,不能改變checkbox 的背景顏色和樣式。
下面是 Safari 瀏覽器 PC 端樣式
下面是 Chrome 移動端樣式
如果是用第三方庫(例如 bootstrap),實際上是在原生的 input 上面進行改變,仍然不能解決瀏覽器兼容性問題。
所以,可以使用自定義的 CheckBox 解決這個問題
<div class="container">
<input type="checkbox" />
<div class="show-box" />
</div>
下面是自定義的CSS
.container {
position: relative;
}
.container input:checked + .show-box {
background: pink;
/* 這裏是背景顏色,可以自定義設置 */
}
.container .show-box {
position: absolute;
top: 0;
left: 0;
width: 16px;
height: 16px;
border-radius: 2px;
border: 1px solid #d8d8d8;
/* 這裏是對勾顏色,可以自定義,和勾選框背景色色差較大 */
background: white;
}
.container .show-box:before {
content: '';
position: absolute;
top: 2px;
left: 4px;
width: 5px;
height: 8px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
可以根據實際需求設置背景色了。
然後,需要把默認的勾選框設置成透明,層級設置較高,那麼界面點擊勾選框就可以改變數據變化了。
如果這裏的對勾選項是響應式的,那麼根據 value 綁定 input 即可實現。