前端

CSS3特效开关

今天浏览网页的时候,看到了如图的这个开关:

演示.gif

第一反应是用了JS控制样式,但尝试了一番后始终达不到这个效果,于是乎看了眼源码,发现这是纯CSS3写的动画!

嗯?不对啊,CSS3能做点击事件?

仔细研究了一下源码,原来是通过:checked选择器实现的。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    body {
        background: #272f42;
    }

    #select {
        display: none;
    }

    .main {
        width: 150px;
        height: 50px;
    }

    .btn {
        width: 130px;
        height: 50px;
        border-radius: 50px;
        box-shadow: 0px 5px 3px rgb(17, 17, 17) inset,
            0px -1px rgb(102, 102, 102) inset;
        background: #141a26;
        cursor: pointer;
        position: relative;
    }

    .round {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: #212a36;
        float: left;
        box-shadow: 2px 0px 2px rgb(17, 17, 17) inset,
            -1px 0px 1px rgb(75, 74, 74) inset;
        position: absolute;
        top: 1px;
        left: 2px;
        transition: all .4s;

    }

    .lamp {
        width: 20px;
        height: 20px;
        float: right;
        border-radius: 50%;
        box-shadow: 0px -2px 4px rgb(17, 17, 17) inset;
        background: #212b3a;
        position: absolute;
        top: 15px;
        left: 160px;
        transition: all .4s;

    }

    input:checked~.label .btn {
        background: #1e2635;
    }

    input:checked~.label .btn .round {
        background: #2e3d50;
        box-shadow: 2px 0px 3px rgb(17, 17, 17) inset,
            -1.3px 0px 1px #b4f2fd inset;
        position: absolute;
        top: 1px;
        left: 81px;
    }

    input:checked~ .lamp {
        background: #b4f2fd;
        box-shadow:
            0px 1px 12px #b4f2fd,
            0px -1px 12px #b4f2fd,
            1px 0px 12px #b4f2fd,
            -1px 0px 12px #b4f2fd;
    }
</style>

<body>
    <div class="main">
        <input type="checkbox" id="select">
        <label for="select" class="label">
            <div class="btn" for="select">
                <div class="round"></div>
            </div>
        </label>
        <div class="lamp"></div>
    </div>
</body>
<script src="./jquery-3.4.1.js"></script>
<script>
    $(function () {
        auto();
        window.onresize = function () {
            auto();
        }
        function auto() {
            var winW = $(window).width();
            var winH = $(window).width();
            $(".main").css({
                position: "absolute",
                left: ($(window).width() - $(".main").outerWidth()) / 2,
                top: ($(window).height() - $(".main").outerHeight()) / 2
            });
        }
    })
</script>

</html>

以后有时间我再写一个注释版的......

附件:CSS3特效开关.zip

微信扫一扫,向我赞赏

微信扫一扫,向我赞赏

微信扫一扫,向我赞赏

支付宝扫一扫,向我赞赏

回复

This is just a placeholder img.