纯css编写开关按钮点击切换

原文地址:
https://www.cnblogs.com/dinghuihua/p/6674106.html
整理:一个英语专业的程序员

效果图预览:

image

完整代码如下:

<!DOCTYPE html>
<html>
<head>
<title>纯css编写开关按钮点击切换</title>
<style type="text/css">
    #toggle-button{ 
        display: none; 
    }
    .button-label{
        position: relative;
        display: inline-block;
        width: 80px;
        background-color: #ccc;
        border: 1px solid #ccc;
        border-radius: 30px;
        cursor: pointer;
    }
    .circle{
        position: absolute;
        top: 0;
        left: 0;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: #fff;
    }
    .button-label .text {
        line-height: 30px;
        font-size: 18px;

        /*
        用来阻止页面文字被选中,出现蓝色
        可以将下面两行代码注释掉来查看区别
        */
       -webkit-user-select: none;
       user-select: none;
    }
    .on { 
        color: #fff; 
        display: none; 
        text-indent: 10px;
    }
    .off { 
        color: #fff; 
        display: inline-block; 
        text-indent: 53px;
    }
    .button-label .circle{
        left: 0;
        transition: all 0.3s;/*transition过度,时间为0.3秒*/
    }

    /*
    以下是checked被选中后,紧跟checked标签后面label的样式。
    例如:div+p 选择所有紧接着<div>元素之后的<p>元素
    */
    #toggle-button:checked + label.button-label .circle{
        left: 50px;
    }
    #toggle-button:checked + label.button-label .on{ 
        display: inline-block; 
    }
    #toggle-button:checked + label.button-label .off{ 
        display: none; 
    }
    #toggle-button:checked + label.button-label{
        background-color: #33FF66;
    }
</style>
</head>
<body>
    <input type="checkbox" id="toggle-button">
   <!--label中的for跟input的id绑定。作用是在点击label时选中input或者取消选中input-->
    <label for="toggle-button" class="button-label">
        <span class="circle"></span>
        <span class="text on">开</span>
        <span class="text off">关</span>
    </label>
</body>
</html>

知识点:

1.label中的for跟input的id绑定。作用是在点击label时选中input或者取消选中input

2.(:checked + 紧邻其后面标签) 的选择器。例如:#toggle-button:checked + label 解释:当id为toggle-button的checked为选中状态时,就选择紧邻其后的label标签

3.user-select: none;这个属性用来阻止页面文字被选中,如果不添加此属性,点击切换开关时,开/关 二字有时候会被选中,出现蓝色背景,如下图:

image
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,273评论 19 139
  • 一:认识jquery jquery是javascript的类库,具有轻量级,完善的文档,丰富的插件支持,完善的Aj...
    xuguibin阅读 1,734评论 1 7
  • HTML 5 HTML5概述 因特网上的信息是以网页的形式展示给用户的,因此网页是网络信息传递的载体。网页文件是用...
    阿啊阿吖丁阅读 4,178评论 0 0
  • FreeCodeCamp - HTML5 and CSS 发现原来在另外一台电脑学 FreeCodeCamp 的时...
    付林恒阅读 9,498评论 2 17
  • 富人孩子和穷人孩子,差的真不仅仅是钱。 前两天,一篇《您没钱,就不要搀和减负这事了》文章大热朋友圈,作为一线小学教...
    不忘初心J阅读 364评论 0 5