JS30

效果展示

相关知识

  1. document.documentElement === document.querySelector(':root') === document.querySelector('html')

  2. style.setProperty(propertyName, value, priority); :为声明了 CSS 样式的对象设置一个新的值。

  3. HTMLElement.dataset 属性:

代码展示

index.html

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

<head>
    <meta charset="UTF-8">
    <title>Scoped CSS Variables and JS</title>
</head>

<body>
    <h2>Update CSS Variables with <span class='hl'>JS</span></h2>

    <div class="controls">
        <label for="spacing">Spacing:</label>
        <input id="spacing" type="range" name="spacing" min="10" max="200" value="10" data-sizing="px">

        <label for="blur">Blur:</label>
        <input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px">

        <label for="base">Base Color</label>
        <input id="base" type="color" name="base" value="#ffc600">
    </div>

    <img src="img/haiou.jpg">

    <style>
        :root {
            --base: #ffc600;
            --spacing: 10px;
            --blur: 10px;
        }

        img {
             500px;
            padding: var(--spacing);
            background: var(--base);
            filter: blur(var(--blur));
        }

        .hl {
            color: var(--base);
        }
        /*
      misc styles, nothing to do with CSS variables
    */

        body {
            color: white;
            font-family: 'helvetica neue', sans-serif;
            font-weight: 100;
            font-size: 50px;
            text-align: center;
            background: #193549;
        }

        .controls {
            margin-bottom: 50px;
        }

        input {
             100px;
        }
    </style>

    <script>
        (function () {
            function changeHandler () {
                // document.documentElement === document.querySelector(':root') === document.querySelector('html')

                document.querySelector(':root').style.setProperty(`--${this.name}`, this.value + (this.dataset.sizing || ''));
            }

            let inputs = document.querySelectorAll('.controls input');

            inputs.forEach(function(input) {
                input.addEventListener('change', changeHandler);
                input.addEventListener('mousemove', changeHandler);
            });
        })();
    </script>

</body>

</html>

参考

原文地址:https://www.cnblogs.com/Ohmy/p/13523908.html