现在很多前端框架或库能实现checkbox自定义样式,这里介绍一下最原生的方式来自定义checkbox样式,并且最早能兼容至IE9浏览器。
不考虑IE9及以下浏览器
使用下列图片:
<!DOCTYPE html>
<html>
<head>
<style>
input[type="checkbox"] {
appearance: none;
-moz-appearance: none;
-ms-progress-appearance: none;
-webkit-appearance: none;
outline: none;
vertical-align: text-top; /* 根据自己需求定义 */
width: 16px;
height: 16px;
background-image: url("https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/3/27/162681b8a147aabe~tplv-t2oaga2asx-image.image");
background-position: 0 0;
}
input[type="checkbox"]:hover {
background-position: -16px 0;
}
input[type="checkbox"]:checked {
background-position: -32px 0;
}
</style>
</head>
<body>
<input type="checkbox">自定义Checkbox
</body>
</html>
css中图片为:
这个方案兼容大部分浏览器,但是IE9是不支持的。
考虑IE9,需要增加label标签
对于IE9来说,appearance属性无效,则需要借助一个新属性label实现。
html结构必须为:
<html>
<body>
<input id="my-id" type="checkbox" /><label for="my-id"></label>
</body>
</html>
<!-- 注意 input 必须带上id,label的for必须指向这个id,否则影响功能 -->
将css样式修改下列代码即可:
input[type="checkbox"] {
display: none;
}
input[type="checkbox"] + label {
width: 16px;
height: 16px;
background-image: url("https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/3/27/162681b8a147aabe~tplv-t2oaga2asx-image.image");
background-position: 0 0;
}
input[type="checkbox"] + label:hover {
background-position: -16px 0;
}
input[type="checkbox"]:checked + label {
background-position: -32px 0;
}
- checkbox样式同样可以使用CSS绘制,而不引用图片
- disabled样式可以借助选择器
input[type="checkbox"][disabled]:checked + label
原文链接:自定义checkbox样式(兼容IE9)