簡體   English   中英

Javascript 滾動事件簡單 animation

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM