自定义checkbox样式(兼容IE9)

如今不少前端框架或库能实现checkbox自定义样式,这里介绍一下最原生的方式来自定义checkbox样式,而且最先能兼容至IE9浏览器。css

不考虑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://user-gold-cdn.xitu.io/2018/3/27/162681b8a147aabe?w=48&h=16&f=png&s=18072"); 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中图片为:html

checkbox-image

这个方案兼容大部分浏览器,可是IE9是不支持的。前端

考虑IE9,须要增长label标签

对于IE9来讲,appearance属性无效,则须要借助一个新属性label实现。web

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://user-gold-cdn.xitu.io/2018/3/27/162681b8a147aabe?w=48&h=16&f=png&s=18072");
  background-position: 0 0;
}
input[type="checkbox"] + label:hover {
  background-position: -16px 0;
}
input[type="checkbox"]:checked + label {
  background-position: -32px 0;
}
复制代码
  1. checkbox样式一样能够使用CSS绘制,而不引用图片
  2. disabled样式能够借助选择器input[type="checkbox"][disabled]:checked + label

原文连接:自定义checkbox样式(兼容IE9)app

相关文章
相关标签/搜索