簡體   English   中英

Javascript 向下滾動到一個部分

[英]Javascript scroll down to a section

我正在我的投資組合網站上工作。 我想在用戶滾動到指定部分時添加一個 css 類。(我想使用 Javascript 事件)

例如,首先使用 css 隱藏一個元素,然后當用戶向下滾動到該部分時,使用 vanilla Javascript 顯示該元素。

<div id="info"> info... </div> 
#info { display :none;}

正在加載 Javascript 代碼😬...

好的,這是一個大問題,您可以使用Intersection Observer但並非所有瀏覽器都支持它,另一種方法是在窗口上使用滾動事件。

function debounce(func, wait = 20, immediate = true) {
    let timeout
    return function() {
      let context = this,
        args = arguments
      let later = function() {
        timeout = null
        if (!immediate) func.apply(context, args)
      }
      let callNow = immediate && !timeout
      clearTimeout(timeout)
      timeout = setTimeout(later, wait)
      if (callNow) func.apply(context, args)
    }
  }

  const images = document.querySelectorAll('img')

  function checkSlide(e) {
    images.forEach(img => {
      const slideInAt = window.scrollY + window.innerHeight - img.height / 2
      const imageBottom = img.offsetTop + img.height
      const isHalfShown = slideInAt > img.offsetTop
      const isNotScrolledPast = window.scrollY < imageBottom
      if (isHalfShown && isNotScrolledPast) {
        img.classList.add('active')
      } else {
        img.classList.remove('active')
      }
    })
  }

  window.addEventListener('scroll', debounce(checkSlide))

這是我在Wes Bos的 javascript30 課程之后制作的代碼,我強烈推薦它並且它是免費的

概括:

函數 debounce 是停止調用事件太多次,超過需要。

const 圖像是我 dom 上的所有圖像,我正在檢查圖像,但您可以檢查要檢查的任何 div。

checkSlide 函數檢查我已經到達但沒有通過每個圖像,在這里你可以檢查你想要的每個 div。

您可以跟蹤窗口的滾動位置和目標元素的頂部位置。 然后,當元素到達某個點(例如窗口高度的一半)時,可以給它一個類來修改一些 css 屬性,如opacitydisplay

let targets = document.querySelectorAll('.target');

window.addEventListener("scroll", function(){
  let doc = document.documentElement;
  let top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

  let windowHeight = window.innerHeight;

  for (i = 0; i < targets.length; ++i) {
    let target = targets[i];
    if(target.offsetTop < (top + (windowHeight/2))) {
      target.classList.add("visible");
    }
    else {
      target.classList.remove("visible");
    }
  }
});

看看這個演示

暫無
暫無

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

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