JavaScript中scroll事件监听器失效:滚动无法修改body背景色
问题原因
你绑定的是window的scroll事件,但实际滚动的是.scroller容器——你在wheel事件里阻止了默认的页面滚动,转而让.scroller元素滚动,所以window的滚动位置根本没变化,自然scroll事件不会触发,控制台也就没有输出。
修复方案
需要把滚动监听绑定到.scroller元素上,同时调整滚动位置和区块位置的计算逻辑,适配容器内滚动的场景:
"use strict"; // Get all the sections with the class "section" const sections = document.querySelectorAll(".section"); const scroller = document.querySelector(".scroller"); // Function to update the background color based on the section in view const updateBackgroundColor = () => { console.log("updateBackgroundColor called"); // 用滚动容器的scrollTop代替window的scrollY const scrollPosition = scroller.scrollTop; console.log("scrollPosition:", scrollPosition); sections.forEach((section) => { // 转换区块位置为滚动容器内的相对位置 const sectionTop = section.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scrollPosition; const sectionBottom = sectionTop + section.offsetHeight; const backgroundColor = section.getAttribute("data-bg-color"); console.log( `Section: ${section.classList}, Top: ${sectionTop}, Bottom: ${sectionBottom}, Background Color: ${backgroundColor}` ); if (scrollPosition >= sectionTop && scrollPosition <= sectionBottom) { // The section is in view if (backgroundColor) { document.body.style.backgroundColor = backgroundColor; } } }); }; // Add an event listener for the "wheel" event on the container scroller.addEventListener("wheel", (event) => { event.preventDefault(); const delta = event.deltaY; if (delta > 0) { scroller.scrollBy({ top: window.innerHeight, behavior: "smooth", }); } else if (delta < 0) { scroller.scrollBy({ top: -window.innerHeight, behavior: "smooth", }); } }); // 把scroll事件绑定到scroller容器上,而不是window scroller.addEventListener("scroll", updateBackgroundColor); // 初始化时触发一次,确保初始背景色正确 updateBackgroundColor();
关键调整点
- 监听对象切换:将
window.addEventListener("scroll")改为scroller.addEventListener("scroll"),监听实际滚动的容器。 - 滚动位置获取:用
scroller.scrollTop获取容器的滚动距离,替代window.scrollY。 - 区块位置计算:修正
sectionTop的计算逻辑,把视口相对位置转换为滚动容器内的相对位置。 - 初始化触发:添加
updateBackgroundColor()调用,确保页面加载时就应用当前可见区块的背景色。
内容的提问来源于stack exchange,提问作者ALI
相关产品推荐
相关产品推荐

