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