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>

效果:

关闭:

开启:

相关推荐
不会敲代码11 小时前
手写 Zustand:三十分钟带你搞懂状态管理库的核心原理
前端·javascript·源码
神奇的程序员1 小时前
重构了自己5年前写的截图插件
前端·javascript·架构
橙淮1 小时前
从优化到安全再到未来 ——JavaScript 全维度技术指南
javascript
UXbot2 小时前
一人独立交付 UI + 前端:AI 驱动 UI 设计工具的五大功能模块深度评测
前端·低代码·ui·设计模式·交互
kobesdu3 小时前
【ROS2实战笔记-19】ROS2 生命周期节点的启动顺序、状态转换陷阱与热备方案
java·前端·笔记·机器人·ros·ros2
诚实可靠王大锤3 小时前
React Native 输入框与按钮焦点冲突解决方案(rn版本0.70.3)
前端·javascript·react native·react.js
kyriewen3 小时前
测试妹子让我写单测,我偷偷用AI一天干完一周的活
前端·chatgpt·cursor
2601_957780843 小时前
Claude Code 2026年最新部署指南:从环境搭建到技能扩展
前端·人工智能·ai编程·claude
zhangfeng11334 小时前
workbuddy 专家 “前端开发师” 结合nvidia-mistral-small-4-119b-2603 项目计划-前端界面开发.md
前端·人工智能·免费
IT_陈寒5 小时前
为什么Java的Stream并行处理反而变慢了?
前端·人工智能·后端