首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 監聽滾動至特定區塊觸發背景切換效果

     編輯:程式設計綜合問答

需求分析

參考 Mailchimp 2012 滾動換背景效果:當頁面滾動到某篇文章區塊時,自動切換背景圖/色。核心邏輯為「檢測目標元素是否進入視口」。

實現方案

方案一:Intersection Observer API(現代、高效)

const sections = document.querySelectorAll('.article-block');
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            document.body.style.backgroundImage = `url(${entry.target.dataset.bg})`;
        }
    });
}, { threshold: 0.5 }); // 50% 可見即觸發

sections.forEach(sec => observer.observe(sec));

方案二:Scroll 事件 + getBoundingClientRect(兼容舊瀏覽器)

function checkVisibility() {
    const triggerPoint = window.innerHeight * 0.3;
    document.querySelectorAll('.article-block').forEach(block => {
        const rect = block.getBoundingClientRect();
        if (rect.top < triggerPoint && rect.bottom > triggerPoint) {
            document.body.style.backgroundColor = block.dataset.bgColor;
        }
    });
}
window.addEventListener('scroll', throttle(checkVisibility, 100));
// 需配合節流函數 throttle 避免頻繁觸發

關鍵點

  • 為每個區塊添加 data-bg 或 data-bg-color 屬性存儲背景資訊。
  • 使用 transition 實現平滑過渡:body { transition: background 0.5s ease; }。
  • Intersection Observer 無需監聽 scroll,效能優越,推薦優先使用。

總結

透過元素可見性檢測驅動背景變更,是實現沉浸式滾動體驗的核心技術。現代瀏覽器請優先使用 Intersection Observer。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved