HTML+CSS3+JS写个的开关

2020-03-10  本文已影响0人  夹板儿孩

写着玩玩,懒得打字了
效果图



下面是代码

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>简单开关</title>
    <style>
        .nameList {
            width: 150px;
        }
        .nameList > div {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .nameList p {
            margin: 0;
            padding: 0;
        }

        /*----------------下列是开关样式---------------*/
        :root{
            --w: 30px;      /*开关宽度*/
            --h: 15px;      /*开关高度*/
        }
        @keyframes on { /* 开关打开动作的动画 */
            0% {transform: translateX(1px);}
            100% {transform: translateX(calc(var(--w) - var(--h) + 1px));}
        }
        @keyframes off { /* 开关关闭动作的动画 */
            0% {transform: translateX(calc(var(--w) - var(--h) + 1px));}
            100% {transform: translateX(1px);}
        }
        @keyframes onBg { /* 开关打开背景变色 */
            0% {background: darkgrey;}
            100% {background: lawngreen;}
        }
        @keyframes offBg { /* 开关关闭背景变色 */
            0% {background: lawngreen;}
            100% {background: darkgrey;}
        }

        .switch {   /* 开关的那个壳 */
            border: 1px solid gray;
            width: var(--w);
            height: var(--h);
            border-radius: 15px;
            display: flex;
            align-items: center;
        }
        .switch i {/* 开关的小白点 */
            display: block;
            width: calc(var(--h) - 2px);
            height: calc(var(--h) - 2px);
            border-radius: 50%;
            margin: 0;
            background: white;
        }
        
        .switch.on {    /*打开开关背景颜色动画*/
            animation: onBg 500ms forwards; /* 使用某个自定义动画  动画完成时间  当动画完成后保持不变 */
        }
        .switch.off {   /*关闭开关背景颜色动画*/
            animation: offBg 500ms forwards;
        }
        .switch.on i {  /*打开开关小白点变化*/
            animation: on 300ms forwards;
        }
        .switch.off i { /*关闭开关小白点动画*/
            animation: off 300ms forwards;
        }
    </style>
</head>
<body>
<div class="nameList">
    <div>
        <p>吕子乔</p>
        <div class="switch on a"><i></i></div>
    </div>
    <div>
        <p>张伟</p>
        <div class="switch off a"><i></i></div>
    </div>
    <div>
        <p>诸葛大力</p>
        <div class="switch on a"><i></i></div>
    </div>
</div>
<script type="text/javascript">
/* 懒得打注释了,简单说下js内容。点击 .switch 时替换class中的on/off */
    document.querySelectorAll(".switch")
        .forEach(function (e) {
            e.onclick = function(){
                if(e.classList.contains("on")){
                    e.classList.replace("on", "off");  //关
                }else if (e.classList.contains("off")) {
                    e.classList.replace("off", "on");  //开
                }
            }
        })
</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读