Skip to content

实现滚动动画

JavaScript
function initCustomAnimateOnScroll() {
  const style = document.createElement("style")
  style.textContent = `
    .custom-animate-on-scroll {
      opacity: 0;
      transform: translateY(100px);
      transition: opacity 0.5s ease-out, transform 0.5s ease-out;
    }
    .custom-animate-on-scroll.visible {
      opacity: 1;
      transform: translateY(0);
    }
  `
  document.head.appendChild(style)

  let observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("visible")
          observer.unobserve(entry.target)
        }
      })
    },
    {
      threshold: 0
    }
  )

  // 处理dom释放的时候 移除IntersectionObserver的监听
  const mutationObserver = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.removedNodes.length > 0) {
        mutation.removedNodes.forEach((node) => {
          if (node.classList && node.classList.contains("custom-animate-on-scroll")) {
            observer.unobserve(node)
          }
        })
      }
    })
  })

  // 观察整个文档的子树变化
  mutationObserver.observe(document.body, {
    childList: true,
    subtree: true
  })

  document.addEventListener("DOMContentLoaded", () => {
    const elements = document.querySelectorAll(".custom-animate-on-scroll")
    elements.forEach((element) => {
      observer.observe(element)
    })
  })
}

initCustomAnimateOnScroll()

世界很美 而你正好有空