You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多页面共享元素时如何解决onscroll滚动事件报错问题

Fix "Uncaught TypeError: background is null" on Scroll (No New JS Files Needed)

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 background to avoid interacting with a null value.
  • You keep all your code in a single file, no need to manage separate homepage scripts.
  • The div element's functionality stays intact across every page, as required.

内容的提问来源于stack exchange,提问作者MaDragon7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 17:22:28