多页面共享元素时如何解决onscroll滚动事件报错问题
Let's break down the issue first: your background element only exists on the homepage, but the scroll listener is added globally across all pages. When users scroll on non-homepage pages, the script tries to access background.style.opacity on a null value, which throws that frustrating error.
Here are two clean, straightforward ways to fix this without splitting your script into separate files:
Option 1: Check for background existence before modifying it
This is the simplest fix—just add a conditional check to ensure background isn't null before you try to update its opacity. The scroll function will still run for the div element (which exists everywhere) but skip the background-related logic on other pages:
// show the div and change background opacity on scroll let background = document.getElementById("background"); let div = document.getElementById("div"); window.addEventListener("scroll", scroll); function scroll() { // Always handle the div since it's present on all pages div.style.display = "block"; // Only modify background if it exists (i.e., we're on the homepage) if (background) { if (window.scrollY >= 500) { background.style.opacity = "0.05"; } else { background.style.opacity = "0.3"; } } }
Option 2: Split scroll logic for global vs. homepage elements
If you prefer to avoid running any background-related code on non-homepage pages entirely, you can separate the scroll listeners—one for the global div element, and another only added when background exists:
let div = document.getElementById("div"); // Global scroll handler for the div (runs on all pages) window.addEventListener("scroll", () => { div.style.display = "block"; }); // Homepage-only scroll handler for background let background = document.getElementById("background"); if (background) { window.addEventListener("scroll", () => { background.style.opacity = window.scrollY >= 500 ? "0.05" : "0.3"; }); }
Why these work:
- Both solutions use a truthy check on
backgroundto avoid interacting with anullvalue. - You keep all your code in a single file, no need to manage separate homepage scripts.
- The
divelement's functionality stays intact across every page, as required.
内容的提问来源于stack exchange,提问作者MaDragon7

