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

使用window.pageYOffset切换背景色时如何解决body元素溢出问题

滚动切换body背景色的问题修复

问题情况

要实现向下滚动每500px切换<body>背景色的效果,但Firefox提示<body>元素导致溢出,给body或html设置overflow:hidden后滚动条直接消失。后来发现是转录代码时出现了两处错误。

错误点分析

  1. CSS语法错误:所有CSS规则块结尾多写了分号(比如body { height: 3000px; };),多余的分号会导致CSS解析异常,进而触发浏览器的溢出提示。
  2. JavaScript拼写错误:window.pageYOffSet里的第二个字母O写成了小写,正确的属性名是window.pageYOffset,拼写错误会导致无法获取正确的滚动距离,切换逻辑完全失效。

修正后的完整代码

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>CHALLENGES</title>
        <style>
            
            body {
                height: 3000px;
            }

            .one {
                background-color: beige;
                transition: all 3s;
            }

            .two {
                background-color: blueviolet;
                transition: all 3s;
            }

            .three {
                background-color: coral;
                transition: all 3s;
            }

            .four {
                background-color: cornflowerblue;
                transition: all 3s;
            }

            .five {
                background-color: darkgoldenrod;
                transition: all 3s;
            }
        </style>
    </head>
    <body class="one">
        
        <h1>Javascript Event Challenges: Challenge 29</h1>
        <p>Scroll Down!</p>

        <script>

            var pageTop;
            var bodyTag = document.querySelector("body");

            window.addEventListener("scroll", function(){

                pageTop = window.pageYOffset;

                switch(true) {
                    case pageTop < 500: bodyTag.className = "one"; break;
                    case pageTop < 1000: bodyTag.className = "two"; break;
                    case pageTop < 1500: bodyTag.className = "three"; break;
                    case pageTop < 2000: bodyTag.className = "four"; break;
                    default: bodyTag.className = "five";
                }
            });

        </script>
    </body>
</html>

说明

修正这两处错误后,既能正常实现滚动每500px切换背景色的效果,也能解决Firefox的溢出提示问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:45:40