首页 > 解决方案 > 我可以使用 javascript 滚动事件更改 div 的宽度和高度吗?

问题描述

我的 div 覆盖了整个屏幕,即 div 的宽度和高度为 100%。我想要一个滚动事件来减小向上滚动时该 div 的宽度和高度,并在向下滚动时增加该 div 的宽度和高度。可能吗?请在这里帮帮我。如果我在这里添加滚动事件,它可能不起作用,因为滚动不会发生,因为 div 适合整个屏幕。

这是我的代码

<html>
    <head>
        <script src="myscript.js"></script>
    </head>
    <body onload="myfunc()">
        <div class="firstdiv">

        </div>
    </body>
</html>
function myfunc(){
    var x = document.getElementsByClassName("firstdiv");
    console.dir(x);
    x[0].style.width = "100%";
    x[0].style.height = "100%";
    x[0].style.background = "red";
    x[0].style.position = "relative";
    x[0].style.top = "0";
    x[0].style.left = "0";
}

标签: javascriptjqueryeventsscroll

解决方案


我希望这可以帮助你

<body style="overflow: scroll; height: 1000px;" onload="scrollDetect()">
    <div class="firstdiv" style="border:1px solid black; margin: 0 auto; width: 200px;height: 200px;">
    </div>

    <script>
        function scrollDetect() {
            let div = document.querySelector('.firstdiv')
            var lastScroll = 0;
            window.onscroll = function () {
                let currentScroll = document.documentElement.scrollTop; // Get Current Scroll Value
                if (currentScroll > 0 && lastScroll <= currentScroll) {
                    lastScroll = currentScroll;
                    div.style.width = '50%'
                    div.style.height = "50%";
                    div.style.background = "red";
                    div.style.position = "relative";
                    div.style.top = "0";
                    div.style.left = "0";
                } else {
                    lastScroll = currentScroll;
                    div.style.width = '200px'
                    div.style.height = '200px'
                }
            };
        }
    </script>
</body>

推荐阅读