css变量与js联动

css变量与js联动

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
        .box {
            width: 300px;
            height: 300px;
            position: absolute;
            left: calc(50% - 150px);
            top: calc(50% - 150px);
        }
        .item {
            width: 8px;
            height: 25px;
            background-color: #000;
            border-radius: 8px;
            position: absolute;
            left: calc(50% - 4px);
            transform-origin: 0 150px;
            transform: rotateZ(calc(var(--index) * var(--base-deg)));
            animation: animate var(--time) linear infinite;
            /* 利用延迟实现动画交替完成 */
            animation-delay: calc(var(--index) * 0.05s - var(--time) / 2);
        }

        @keyframes animate {
            0%,
            50% {
            background: #050c09;
            box-shadow: none;
            }
            51%,
            100% {
            background: #38d2dd;
            box-shadow: 0 0 5px #38d2dd, 0 0 15px #38d2dd, 0 0 30px #38d2dd,
                0 0 60px #38d2dd, 0 0 90px #38d2dd;
            }
        }
        </style>
    </head>
    <body>
        <div class="box">
        <div class="item"></div>
        </div>
        <script>
        const ITEM_NUM = 30;
        const baseDeg = 360 / ITEM_NUM;
        const box = document.querySelector(".box");
        box.style.setProperty("--time", `${ITEM_NUM * 0.1}s`);
        box.style.setProperty("--base-deg", `${baseDeg}deg`);
        for (let i = 0; i < ITEM_NUM; i++) {
            const div = document.createElement("div");
            div.classList.add("item");
            div.style.setProperty("--index", i);
            box.appendChild(div);
        }
        </script>
    </body>
    </html>

如上代码,可通过js动态生成变量与css的变量与函数进行配合达到意想不到的效果


css变量与js联动
http://localhost:8090/archives/cssbian-liang-yu-jslian-dong
作者
Administrator
发布于
2026年01月30日
许可协议