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>

效果:

关闭:

开启:

相关推荐
清灵xmf11 分钟前
npm install --legacy-peer-deps:它到底做了什么,什么时候该用?
前端·npm·node.js
超级大只老咪1 小时前
字段行居中(HTML基础语法)
前端·css·html
IT_陈寒1 小时前
Python开发者必看!10个高效数据处理技巧让你的Pandas代码提速300%
前端·人工智能·后端
只_只1 小时前
npm install sqlite3时报错解决
前端·npm·node.js
FuckPatience1 小时前
Vue ASP.Net Core WebApi 前后端传参
前端·javascript·vue.js
数字冰雹1 小时前
图观 流渲染打包服务器
服务器·前端·github·数据可视化
JarvanMo1 小时前
Flutter:我在网上看到了一个超炫的动画边框,于是我在 Flutter 里把它实现了出来
前端
returnfalse1 小时前
前端性能优化-第三篇(JavaScript执行优化)
前端·性能优化
yuzhiboyouye1 小时前
前端架构师,是架构什么
前端·架构
全马必破三1 小时前
Buffer:Node.js 里处理二进制数据的 “小工具”
前端·node.js