简体   繁体   English

Javascript 滚动事件简单 animation

[英]Javascript scroll event simple animation

I want the square to be yellow with each scroll down, and the square to be green with each scroll up.我希望每次向下滚动时正方形为黄色,每次向上滚动时正方形为绿色。 This snippet works almost the way I want it to, because what I want happens only when the square is no longer fully visible on the viewport.这个片段几乎按照我想要的方式工作,因为只有当正方形在视口上不再完全可见时,我想要的才会发生。 I would like the scroll down to be yellow and the scroll up to be green.我希望向下滚动为黄色,向上滚动为绿色。

 const square = document.querySelector('.square'); const squarePos = square.getBoundingClientRect().top; console.log(squarePos); window.addEventListener('scroll',mouse=>{ const scrollTop = window.scrollY; if (scrollTop >squarePos) { square.style.background = "yellow"; } else{ square.style.background = "green"; } });
 .square{ width:100px; height:100px; position:relative; margin:0 auto; background:red; top:200px; }.content{ width:100vw; height:150vh; }
 <div class = 'square'></div> <div class = 'content'></div>

You need to compare your squarePos with the previous square pos, not the client y.您需要将您的squarePos与之前的 square pos 进行比较,而不是客户端 y。 Set the position with let, and update the value after each event listener callback.用let设置position,每次事件监听回调后更新值。

 const square = document.querySelector('.square'); let squarePos = square.getBoundingClientRect().top; window.addEventListener('scroll', mouse => { if (square.getBoundingClientRect().top > squarePos) { square.style.background = "yellow"; } else{ square.style.background = "green"; } squarePos = square.getBoundingClientRect().top; });
 .square{ width:100px; height:100px; position:relative; margin:0 auto; background:red; top:200px; transition: background 200ms ease; }.content{ width:100vw; height:150vh; }
 <div class = 'square'></div> <div class = 'content'></div>

Maybe something like this?也许是这样的?

The idea is get the previous scroll location (y) and compare to the current scroll location.这个想法是获取以前的滚动位置 (y) 并与当前滚动位置进行比较。

If the previous is bigger, then, it scroll up, otherwise scroll down如果前一个更大,则向上滚动,否则向下滚动

 const square = document.querySelector('.square'); const squarePos = square.getBoundingClientRect().top; let oldpos = 0; window.addEventListener('scroll', mouse => { const scrollTop = window.pageYOffset; if (scrollTop > oldpos) { square.style.background = "yellow"; } else { square.style.background = "green"; } oldpos = scrollTop });
 .square { width: 100px; height: 100px; position: relative; margin: 0 auto; background: red; top: 200px; }.content { width: 100vw; height: 150vh; }
 <div class='square'></div> <div class='content'></div>

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

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