[英]Creating a Simple Element Scroll Animation (javascript/css)
[英]Javascript scroll event simple animation
我希望每次向下滚动时正方形为黄色,每次向上滚动时正方形为绿色。 这个片段几乎按照我想要的方式工作,因为只有当正方形在视口上不再完全可见时,我想要的才会发生。 我希望向下滚动为黄色,向上滚动为绿色。
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>
您需要将您的squarePos
与之前的 square pos 进行比较,而不是客户端 y。 用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>
也许是这样的?
这个想法是获取以前的滚动位置 (y) 并与当前滚动位置进行比较。
如果前一个更大,则向上滚动,否则向下滚动
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.