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>

效果:

关闭:

开启:

相关推荐
打瞌睡的朱尤20 分钟前
Vue day9 购物车,项目,vant组件库,vw,路由
前端·javascript·vue.js
星火开发设计2 小时前
模板参数:类型参数与非类型参数的区别
java·开发语言·前端·数据库·c++·算法
cc.ChenLy4 小时前
【CSS进阶】毛玻璃效果与代码解析
前端·javascript·css
何中应4 小时前
使用Jenkins部署前端项目(Vue)
前端·vue.js·jenkins
西门吹-禅4 小时前
node js 性能处理
开发语言·javascript·ecmascript
3秒一个大5 小时前
JWT 登录:原理剖析与实战应用
前端·http·代码规范
一只大侠的侠5 小时前
React Native for OpenHarmony:日期范围选择器实现
javascript·react native·react.js
NEXT065 小时前
2026 技术风向:为什么在 AI 时代,PostgreSQL 彻底成为了全栈工程师的首选数据库
前端·数据库·ai编程
NEXT065 小时前
拒绝“盲盒式”编程:规范驱动开发(SDD)如何重塑 AI 交付
前端·人工智能·markdown
@大迁世界5 小时前
仅用 CSS 实现元素圆形排列的方法
前端·css