美文网首页
自定义checkbox和radio

自定义checkbox和radio

作者: Nic_ofh | 来源:发表于2017-08-19 23:39 被阅读0次

基于原生的checkbox和radio在网页中显示比较丑,所以我们追求美观的同时不能忍受丑陋的勾选框。

实现办法有两种办法:

  1. 用css来实现
  2. 用背景图来实现

原理:通过伪类:checked和伪元素::after来实现的

一、用css来实现(减少图片对http的请求)

      input[type=radio], input[type=checkbox] {
      visibility: hidden;
    }

    input[type=checkbox]::after, input[type=radio]::after {
      border-radius: 50%;
      display: inline-block;
      width: 16px;
      height: 16px;
      line-height: 16px;
      content: ' ';
      border: 1px solid #000;
      visibility: visible;
    }

    input[type=radio]:checked::after, input[type=checkbox]:checked::after {
      display: inline-block;
      border-radius: 50%;
      width: 16px;
      height: 16px;
      line-height: 16px;
      content: ' ';
      background: #d73d32;
      border: none;
      visibility: visible;
    }

二、背景图来实现勾选效果(还原度较高)

        input[type=radio]{
            visibility: hidden;
        }
        input[type=radio]:checked::after{
            background-image: url('./img/sprite.png');
            background-repeat: no-repeat;
            background-position: -59px -10px;
            visibility: visible;
        }
        input[type=radio]::after{
            content: ' ';
            display: block;
            height: 20px;
            width: 20px;
            background-image: url('./img/sprite.png');
            background-repeat: no-repeat;
            background-position: -24px -10px;
            visibility: visible;
        }
        input[type=checkbox]{
            visibility: hidden;
        }

        input[type=checkbox]:checked::after{
            background-image: url('./img/sprite.png');
            background-repeat: no-repeat;
            background-position: -60px -31px;
            visibility: visible;
        }
        input[type=checkbox]::after{
            content: '';
            display: block;
            height: 20px;
            width: 20px;
            background-image: url('./img/sprite.png');
            background-repeat: no-repeat;
            background-position: -25px -32px;
            visibility: visible;
        }

相关文章

网友评论

      本文标题:自定义checkbox和radio

      本文链接:https://www.haomeiwen.com/subject/azyxdxtx.html