html实现iphone同款开关

一、背景

想实现一个开关的按钮,来触发一些操作,网上找了总感觉看着别扭,忽然想到iphone的开关挺好,搞一个

二、代码实现

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>开关按钮</title>
    <style>
        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            -webkit-transition: .4s;
            transition: .4s;
            border-radius: 34px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            -webkit-transition: .4s;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: #4CD964;
        }

        input:focus + .slider {
            box-shadow: 0 0 1px #4CD964;
        }

        input:checked + .slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        .slider.round {
            border-radius: 34px;
        }

        .slider.round:before {
            border-radius: 50%;
        }
    </style>
</head>
<body>
<div>
    <label class="switch">
        <input type="checkbox" id="mySwitch" onchange="updateStatus()">
        <span class="slider round"></span>
    </label>
</div>
<script>
    function updateStatus() {
        let switchStatus = document.getElementById("mySwitch").checked;
        if (switchStatus) {
            console.log("已开启");
        } else {
            console.log("已关闭");
        }
    }
</script>
</body>
</html>

效果:

关闭:

开启:

相关推荐
广州华水科技几秒前
单北斗GNSS在桥梁形变监测中的应用与技术进展分析
前端
我讲个笑话你可别哭啊2 分钟前
鸿蒙ArkTS快速入门
前端·ts·arkts·鸿蒙·方舟开发框架
CherryLee_12104 分钟前
基于poplar-annotation前端插件封装文本标注组件及使用
前端·文本标注
特立独行的猫a10 分钟前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
周航宇JoeZhou13 分钟前
JB2-7-HTML
java·前端·容器·html·h5·标签·表单
代码小库15 分钟前
【课程作业必备】Web开发技术HTML静态网站模板 - 校园动漫社团主题完整源码
前端·html
VT.馒头15 分钟前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
云计算DevOps-韩老师17 分钟前
HTML 中的行级元素(inline)、块级元素(block)、行内块元素(inline-block)
html
珹洺21 分钟前
Bootstrap-HTML(二)深入探索容器,网格系统和排版
前端·css·bootstrap·html·dubbo
BillKu22 分钟前
VS Code HTML CSS Support 插件详解
前端·css·html