如何用图片代替多选、单选按钮

在前端开发过程中,对于单选、多选按钮,遇到的问题大致有如下两个:

第一,对于类似于单选多选答题,更希望能够实现点击选项也能够使得按钮选中,这得如何实现呢?

第二,默认的单选、多选按钮颜值是真得很low啊,可否进行微整呢?

一、实现点击选项选中按钮选中

有两种方式:

1、将label标签把选框和文本一起包围 

<label>
    <input type="checkbox" value="1"  name="checkboxDemo" />选项一
</label>
<label>
    <input type="checkbox" value="2"  name="checkboxDemo" />选项二
</label>

2、要使label的for 和选框的id名字对应

<input type="checkbox" id="name1" />
<label for="name1">选项2</label>
<input type="checkbox" id="name2" />
<label for="name2">选项2</label>

二、提升一下颜值

如何提升颜值呢?方法比较简单,利用上述点击选项即可使按钮选中,将默认的单选或者多选按钮隐藏,用图片替代。

第一种方式,直接上代码,利用了伪选择器

<head>
     <style>
        input{
           display: none
        }
        label{
           background: url(img/option.png) no-repeat left center;
           line-height: 28px; 
           display: block; padding: 5px 0 5px 35px;
        }
        input[type=checkbox]:checked+label{
          background: url(img/option_on.png) no-repeat;
        }
    </style>
</head>
<body>
    <input type="checkbox" id="name1" />
    <label for="name1">选项2</label>
    <input type="checkbox" id="name2" />
    <label for="name2">选项2</label>

</body>

第二种方式,则需要使用js

<head>
    <script type="text/javascript">
        $(function(){
            $("input[type='checkbox']").click(function(){
                if($(this).is(':checked')){
                    $(this).attr("checked","checked");
                    $(this).parent().removeClass("off").addClass("on");
                }else{
                    $(this).removeAttr("checked");
                    $(this).parent().removeClass("on").addClass(" off");
                }
            });

        });
   </script>
   <style>
        label{
              background: url(img/option.png) no-repeat left center;  
              line-height: 28px; 
              display: block; padding: 5px 0 5px 35px;
        }
        .off{
            background: url(img/option.png) no-repeat left center;
        }
        .on{
            background: url(img/option_on.png) no-repeat left center;
        }
        input{display: none}
    </style>
</head>
<body>
    <label>
      <input type="checkbox" value="1"  name="checkboxDemo" />选项一
    </label>
    <label>
      <input type="checkbox" value="2"  name="checkboxDemo" />选项二
    </label>
</body>

上效果图:

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值