在jquery中有一个持续更改字体大小的滑块,但需要帮助才能转换为vanilla js

xyhw6mcr  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(225)

现在我有了这个jquery字体调整滑块,但需要在vanilla.js中使用它。它工作正常,但我无法将其转换为纯javascript。
我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link href="app.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <div class="font-slider">
        <input type="range" min="17" max="28" value="22" step="1" />
    </div>
    <div>
        <h1>Changing Font Size</h2>
            <p>I am just a boring text, existing here solely for the purpose of this demo</p>
            <p>And I am just another one like the one above me, because two is better than having only one</p>
            <a href="#">I am a link, don't click me!</a>
    </div>
    <script>
        var curSize = localStorage.getItem("saveSize");
        if (curSize) {
            var saveSize = curSize;
            $('body').css('font-size', saveSize + 'px');
            var setSize = $('body').css('font-size');
        }
        $('.font-slider input[type="range"]').on("input change", function () {
            var newSize = $(this).val(),
                defaultSize = $("body").css("font-size"),
                minSize = 17,
                maxSize = 28;

            if (newSize <= maxSize && newSize >= minSize) {
                $("body").css("font-size", newSize + "px");

                localStorage.setItem("saveSize", newSize);
            }
        });
    </script>
</body>
</html>
ipakzgxi

ipakzgxi1#

尝试:

var curSize = localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body

if (curSize) {
    var saveSize = curSize;
    body.style.fontSize = saveSize + 'px';
}

slider.addEventListener("input", function (e) {
    var newSize = this.value,
        defaultSize = body.style.getPropertyValue('font-size'),
        minSize = 17,
        maxSize = 28;

    if (newSize <= maxSize && newSize >= minSize) {
        body.style.fontSize = newSize + 'px';

        localStorage.setItem("saveSize", newSize);
    }
});

相关问题