zoukankan      html  css  js  c++  java
  • [CSS揭秘]自定义单选框和复选框

    很多Web前端工程师肯定都会遇到过,在项目中,UI设计师跑来跟你说,我这个地方的表单控件需要设计成这个样子那个样子。但是用CSS却不能够修改这些控件的默认样式,于是乎,只能通过div+javascript技术来进行模拟。特别是在如今移动端的崛起时代,更加注重用户的体验。于是就更加需要这样一种hack技术。

    如果对如今的前端框架有过了解,都会知道组件这个概念。那么在这些框架中,都会提供一些单选框或复选框按钮组件。可见大家之前受到表单元素的默认样式的毒害有多深。

    今天先给大家简单介绍一下如何通过CSS来实现单选框和复选框组件。

    原理其实很简单,单选框就是input[type='radio']而复选框就是input[type='checkbox'] 利用label元素的for属性与表单控件的id相互关联就能起到触发开关的作用。而label元素又是可以通过CSS自定义默认样式的。于是就可以将真正的input标签隐藏起来。

    <input type="checkbox" id="awesome"/>
    <label for="awesome">AweSome!</label>
    input[type="checkbox"]{
        position: absolute;
        clip: rect(0,0,0,0);;
    }
    input[type="checkbox"] + label::before{
        content: "a0";
        display: inline-block;
        vertical-align: 0.2em;
        width: 0.8em;
        height: 0.8em;
        margin-right: 0.2em;
        border-radius: 0.2em;
        background: silver;
        text-indent: 0.15em;
        line-height: 0.65;
    }
    input[type="checkbox"]:checked + label::before{
        content: "2713";
        background: yellowgreen;
    }
    input[type="checkbox"]:focus + label::before{
        box-shadow: 0 0 0.1em 0.1em #58a;
    }
    input[type="checkbox"]:disabled + label::before{
        background: gray;
        box-shadow: none;
        color: #555;
    }

    实战: 开关式按钮

    根据前面介绍的方法,可以很容易模拟出一个开关式按钮,也就是直接修改label标签样式使得其看起来和按钮一致。

    input[type="radio"]{
        position: absolute;
        clip: rect(0,0,0,0);  
    }
    input[type="radio"] + label{
        display: inline-block;
        padding: 0.3em 0.5em;
        background: #ccc;
        background-image: linear-gradient(#ddd, #bbb);
        border: 1px solid rgba(0,0,0,0.2);
        border-radius: 0.3em;
        box-shadow: 0 1px white inset;
        text-align: center;
        text-shadow: 0 1px 1px white;
    }
    input[type="radio"]:checked + label,
    input[type="radio"]:active + label{
        box-shadow: 0.05em 0.1em 0.2em rgba(0,0,0,0.6) inset;
        border-color: rgba(0,0,0,0.3);
        background: #bbb;
    }

    原理很简单,当你掌握了这种方法之后,可以配合JS来实现更多有用的表单控件组件。

  • 相关阅读:
    File类 文件过滤器
    LinkedList类的基本方法的用法
    Execption异常 手动和自动抛除异常
    Xshell连接Linux慢问题解决办法
    Liunx网络技术管理及进程管理
    Liunx中三种网络模式配置及Xshell连接
    LInux命令英文全称
    Liunx中fstab文件详解
    20190411RAID磁盘阵列及CentOS7系统启动流程
    20190410Linux中磁盘管理及LVM(week2day1)
  • 原文地址:https://www.cnblogs.com/joyjoe/p/7277018.html
Copyright © 2011-2022 走看看