简体   繁体   中英

How can I zoom in on a div element on scroll using javascript?

What I'm trying to achieve here is that when I scroll on a particular div here .ball , it should scale up to 1.5.
but when I'm not scrolling on that ball div it should shrink down to it's original height and width.
Here I'm using window method to do this trick and as soon as I scroll ball scale up which isn't what I'm trying to do. What can I use instead of window method and is there any other approach to do achieve this?

 const ball = document.querySelector('.ball'); window.addEventListener('scroll', ()=> { if (scroll) { ball.classList.add('active'); } else { ball.classList.remove('active'); } });
 .ball { height: 200px; width: 200px; border-radius: 100%; background-color: orange; }.ball.active { transform: scale(1.5); position: fixed; } body { height: 150vh; }
 <div class="ball"></div>

I would use a setTimeout function to remove the class after a short period after the scroll. Do not forget to clear the timeout otherwise it will lead to weird behaviour. (as suggested by Lakshya when I was answering to the question).

To make the ball smoothly transition, I would add a css transition as shown bellow.

 const ball = document.querySelector('.ball'); const container = document.querySelector('.container') let scrollTimeout; container.addEventListener('scroll', ()=> { ball.classList.add('active'); clearTimeout(scrollTimeout); scrollTimeout = setTimeout(()=> ball.classList.remove('active'), 100); });
 .ball { height: 200px; width: 200px; border-radius: 100%; background-color: orange; transition: transform 0.3s ease; position: fixed; top: 50px; left: 50px; }.ball.active { transform: scale(1.5); }.container{ width: 100%; background: red; overflow: scroll; height: 500px; }.inside_container{ position: relative; width: 100%; height: 2000px; }
 <div class="container"> <div class="inside_container"> <div class="ball"></div> </div> </div>

One of the approaches could be delaying the removal of .active class on ball by 200 ms such that each time you try to scroll again, the timer is cleared and a new one starts to do the same. A debounce approach in a nutshell.

 const ball = document.querySelector('.ball'); let scrollTimeout; window.addEventListener('scroll', ()=> { ball.classList.add('active'); clearTimeout(scrollTimeout); scrollTimeout = setTimeout(()=> ball.classList.remove('active'),200); });
 .ball { height: 200px; width: 200px; border-radius: 100%; background-color: orange; }.ball.active { transform: scale(1.5); position: fixed; } body { height: 150vh; }
 <div class="ball"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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