当前位置: 代码网 > it编程>网页制作>Css > 纯CSS实现开关按钮切换效果简洁易用

纯CSS实现开关按钮切换效果简洁易用

2023年10月11日 Css 我要评论
纯CSS实现开关按钮切换效果简洁易用这篇文章主要为大家介绍了纯CSS实现开关按钮切换效果简洁易用,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪... 23-10-11

效果图预览

完整代码如下

<!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;这个属性用来阻止页面文字被选中,如果不添加此属性,点击切换开关时,开/关 二字有时候会被选中,出现蓝色背景,如下图:

以上就是纯css编写开关按钮点击切换效果实现的详细内容,更多关于css开关按钮点击切换的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com