doubleyong
管理员
管理员
  • 最后登录2025-12-02
  • 发帖数1198
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
阅读:5482回复:0

[css]如何高效自定义单选框的样式

楼主#
更多 发布于:2020-03-07 08:57
方法1:可以通过jquery, 来做一个假的单选,用户点击切换图片(这种方法需要js的操作配合,方法2可以不用js)
 js实现自定义单选框的样式,
代码如下:
html:
<div>
  <input type="radio" id="nba" checked="checked" name="sport" value="nba">
  <label name="nba" class="checked" for="nba">NBA</label>
  <input type="radio" id="cba" name="sport" value="cba">
  <label name="cba" for="cba">CBA</label>
</div>
css:
input[type="radio"] {
  margin: 3px 3px 0px 5px;
  display: none;
}
label {
  padding-left: 20px;
  cursor: pointer;
  background: url(bg.gif) no-repeat left top;
}
label.checked {
  background-position: left bottom;
}
jquery:
$(function() {
  $('label').click(function(){
    var radioId = $(this).attr('name');
    $('label').removeAttr('class') && $(this).attr('class', 'checked');
    $('input[type="radio"]').removeAttr('checked') && $('#' + radioId).attr('checked', 'checked');
  });
});


方法二:


不需要用到js, 而是纯css, 个人推荐使用此方法,巧用了将radio隐藏,然后通过label的for属性来改变radio的选中状态,在利用:checked伪类与兄弟选择器(+)来修改label的样式。从而无需使用js


代码如下:
html:
<div>
                <input type="radio" name="paixu" id="paixu1" checked>
                <label for="paixu1" style="cursor:pointer">按热门排序</label>
                <input type="radio" name="paixu" id="paixu2">
                <label for="paixu2" style="cursor:pointer">按时间排序</label>
                <input type="radio" name="paixu" id="paixu3">
                <label for="paixu3" style="cursor:pointer">按评价排序</label>
            </div>
css:

div>input{
    display: none;
}
div>label{
    position: relative;
    margin-right: 34px;
}
div>label::before{
    display: inline-block;
    content: "";
    width: 16px;
    height: 16px;
    border-radius: 50%;
    border: 1px solid rgb(219, 219, 219);
    margin-right: 6px;
    vertical-align: bottom;
}
div>input:checked+label::before{
    background-color: rgb(239, 66, 56);
}
div>input:checked+label::after{
    display: inline-block;
    content: "";
    width: 6px;
    height: 6px;
    border-radius: 50%;
    position: absolute;
    left: 6px;
    bottom: 6px;
    background-color: white;
}


参考文献:
https://segmentfault.com/q/1010000000521764
https://www.cnblogs.com/zhangzhiyong/p/9581110.html
知识需要管理,知识需要分享
游客


返回顶部

公众号

公众号