CSS实现开关按钮点击切换

AI 概述
纯 css 编写开关按钮点击切换效果。 效果图如下: 完整代码: <!DOCTYPE html> <html> <head> <title>纯 css 编写开关按钮点击切换</title> <style type="text/css"> #toggle-button{ display: none; } .button-label{ position: relative...

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

效果图如下:

CSS 实现开关按钮点击切换

完整代码:

<!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实现开关按钮点击切换的文章就介绍到这了,更多相关内容请搜索码云笔记以前的文章或继续浏览下面的相关文章,希望大家以后多多支持码云笔记。

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 admin@mybj123.com 进行投诉反馈,一经查实,立即处理!
重要:如软件存在付费、会员、充值等,均属软件开发者或所属公司行为,与本站无关,网友需自行判断
码云笔记 » CSS实现开关按钮点击切换

发表回复