簡體   English   中英

如何在雙向滾動 js 時執行 animation(頂部/底部)

[英]How to do animation on scroll in js on both ways (top/bottom)

我通過使用邊界客戶端在 JS 中創建了一個小動畫。 向下滾動直到出現文本/內容后,我通過應用 CSS 中的“.active”將其不透明度更改為 1。 當我再次向上滾動到元素上方時,不透明度變回 0(因為“.active”被帶走了)。

問題是當我從下面向上滾動到內容元素時,我想讓同樣的事情發生。 一旦用戶低於內容元素,不透明度應 go 為 0,然后當他們向上滾動(因此內容元素再次出現)時,不透明度應 go 為 1。所以它使 Z6F1C25ED15230962B1 在兩個方向上都可以工作在scrollrevealjs的首頁。

document.addEventListener('scroll',()=>{
  let content = document.querySelector('.text');
  let contentPositiontop = content.getBoundingClientRect().top;
  let screenPosition = window.innerHeight ;
  if (contentPositiontop < screenPosition){   
    content.classList.add('active');                                                                
  }
  else{
    content.classList.remove('active');
  }
});

.text{
  transform: translateX(700px) translateY(1000px);
  font-family: Inter;
  font-weight: 800;
  font-size: 40px;
  opacity: 0;
  transition: all 2s ease;
  position: absolute;
}

.active{
  opacity: 1;
}

您只需要檢查內容元素底部和頂部的高度。

(對於頂部,我們需要添加屏幕高度(window.innerHeight),因為我們將其 position 與屏幕底部進行比較。底部不需要此值,因為我們將其 position 與頂部進行比較屏幕,其垂直 position 為 0。)

當底部和頂部都在范圍內時,我們顯示內容元素。

(如果內容元素的高度由於某種原因大於屏幕的高度,則必須選擇 0 到 window.innerHeight 之間的值來觸發轉換。)

 document.addEventListener('scroll',() => { const content = document.querySelector('.text'), top = content.getBoundingClientRect().top, bottom = content.getBoundingClientRect().bottom; if (top < innerHeight && bottom > 0){ content.classList.add('active'); } else{ content.classList.remove('active'); } });
 .spacer{ height: 104vh; }.text{ height: 100vh; background: blue; transform: translateX(20px); opacity: 0; transition: all 2s ease; }.active{ opacity: 1; }
 <div class="spacer"> </div> <div class="text"></div> <div class="spacer"> </div>.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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