checkbox、radio设置自定义样式

时间:2023-03-08 22:58:41
checkbox、radio设置自定义样式

  老生常谈,做一个简单的记录。浏览器自带的checkbox和radio样式可能不符合项目要求,通常要做一些自定义样式设置,目前基本的解决思路都是将input[type=checkbox/radio]隐藏,用label去与input做联动处理,具体实现方法有以下两种:

 <!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
/* 方法1 */ label {
display: inline-block;
width: 15px;
height: 15px;
background: url('../../../assets/img/unchecked.svg') no-repeat 100% 100%;
} input[type="checkbox"]:checked+label {
background: url('../../../assets/img/checked.svg') no-repeat 100% 100%;
}
/* 方法2 */ #test+span {
display: inline-block;
width: 15px;
height: 15px;
background: url('../../../assets/img/unchecked.svg') no-repeat 100% 100%;
} #test:checked+span {
background: url('../../../assets/img/checked.svg') no-repeat 100% 100%;
}
</style>
<title>checkboxAndRadio</title>
</head> <body ng-app="app">
<div>方法1</div>
<input type="checkbox" id="checkbox" style="display: none;">
<label for="checkbox"></label><br>
<div>方法2</div>
<input type="checkbox" id="test" style="display: none;">
<span></span>
<script>
document.getElementsByTagName('span')[0].addEventListener('click', function(e) {
this.previousElementSibling.checked = !this.previousElementSibling.checked;
})
</script>
</body> </html>

  第一种方式必须要设置元素id,如果表单过多将导致命名很纠结;第二种可以简单的写一个事件监听,去动态改变checkbox的选中状态,以此来达到动态切换的目的。在利用框架进行开发应用时,只需要进行简单的封装即可使用,radio实现同上,效果图如下:

checkbox、radio设置自定义样式