前言:有些需求是想要单选的效果,但希望是多选框的样式。也可以说是,多选框实现单选的功能。所以我们来实现一下
1.首先,我们来看一下默认情况下的单选框,代码及效果图如下:
请选择您喜欢的水果:<br>
<input type="radio" name="fruits" id="banana" value="香蕉" class="radio" checked="checked">
<label for="banana" class="radio">香蕉</label>
<input type="radio" name="fruits" id="apple" value="苹果" class="radio">
<label for="apple" class="radio">苹果</label>
<input type="radio" name="fruits" id="orange" value="橙子" class="radio">
<label for="orange" class="radio">橙子</label>
2.思路:调整单选框的用样式为多选框的样式(自定义样式)
3.实现:在原有的代码基础上,调整CSS样式,如下(含备注)
<style>
/* 透明度为0,即不显示原有的单选框 */
input[type='radio'].radio {
opacity:0;
}
/* 新的单选框样式 */
label.radio {
background: url('img/dd.png') no-repeat;
padding-left: 20px;
}
/* 选中的单选框样式*/
input[type='radio'].radio:checked + .radio {
background:url('img/cc.png') no-repeat;
}
</style>
CSS样式中的两个图为选中和默认情况下的多选框样式(可自行在网上下载),如下图
加上CSS样式后,看一下效果,如下图