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>

效果:

关闭:

开启:

相关推荐
FogLetter6 分钟前
React Fiber 机制:让渲染变得“有礼貌”的魔法
前端·react.js
不想说话的麋鹿12 分钟前
「项目前言」从配置程序员到动手造轮子:我用Vue3+NestJS复刻低代码平台的初衷
前端·程序员·全栈
JunpengHu22 分钟前
esri-leaflet介绍
前端
zm43531 分钟前
bpmn.js 自定义绘制流程图节点
前端·bpmn-js
小杨梅君33 分钟前
探索现代 CSS 色彩:从 HSL 到 OKLCH,打造动态色阶
前端·javascript·css
刺客_Andy34 分钟前
React 第五十一节 Router中useOutletContext的使用详解及注意事项
前端·javascript·react.js
宁雨桥1 小时前
基于 Debian 服务器的前端项目部署完整教程
服务器·前端·debian
JunpengHu1 小时前
CSS 滤镜(filter)
前端
你说啥名字好呢1 小时前
【React Fiber的重要属性】
javascript·react.js·ecmascript
时雨__1 小时前
uniapp转鸿蒙app内部测试发布过程——踩坑记录
前端·harmonyos