简体   繁体   English

我可以使用 javascript 滚动事件更改 div 的宽度和高度吗?

[英]Can I change the width and height of a div using javascript scroll event?

My div covers the whole screen ie, the div width and height is 100%.我的 div 覆盖了整个屏幕,即 div 的宽度和高度是 100%。 And i want a scroll event to decrease the width and height of that div on scroll up and increase the width and height of the div on scroll down.我想要一个滚动事件来减少向上滚动时该 div 的宽度和高度,并在向下滚动时增加 div 的宽度和高度。 Is it possible?是否可以? Please help me out here.If i add scroll event here it doesn't work maybe because the scroll doesn't happen as the div fits the whole screen.请在这里帮助我。如果我在这里添加滚动事件它不起作用可能是因为滚动不会发生,因为 div 适合整个屏幕。

here is my code这是我的代码

<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";
}

i hope this can help you我希望这可以帮助你

<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>

You probably want to start here: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll您可能想从这里开始: https : //developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll

You can set the .onscroll event on the area you want to change the size of, or perhaps on the entire body if you want the user to be able to scroll past the element you're resizing.您可以在要更改大小的区域上设置.onscroll事件,或者如果您希望用户能够滚动经过您正在调整大小的元素,也可以在整个身体上设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM