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>

效果:

关闭:

开启:

相关推荐
wizardpisces8 小时前
Claude Code 是 Angular,Codex 是 Vue,DeepSeek 想当 React
前端·人工智能
一条溺水的鱼8 小时前
一次讲透 JS 原型链 —— prototype、__proto__ 和 constructor 到底啥关系
javascript
三乐2288 小时前
一文搞懂 JS 事件流:捕获、冒泡、事件委托
javascript·html
计算机魔术师8 小时前
纽约时报诉 OpenAI 案新解封文件:微软与 OpenAI 内部承认 LLM 建立在窃取之上并引发 Doom Loop
前端
PedroQue998 小时前
uni-app x 事件通信插件重磅上线
前端·uni-app
强尼5308 小时前
WeasyPrint 技术入门指南——用 Web 技术生成 PDF 的专业库使用详解
html
lichenyang4538 小时前
ASCF WebView:H5 为什么收不到元服务消息?
前端
莪_幻尘9 小时前
从 0 到 1 搭建你的 AI Agent 平台:当 Agent 有了工厂,人人都能造同事
前端·ai编程
yuzhiboyouye9 小时前
XML写接口适用场景举例
java·服务器·前端
IMPYLH9 小时前
HTML 的 <slot> 元素
前端·网络·html