使用window.pageYOffset切换背景色时如何解决body元素溢出问题
滚动切换body背景色的问题修复
问题情况
要实现向下滚动每500px切换<body>背景色的效果,但Firefox提示<body>元素导致溢出,给body或html设置overflow:hidden后滚动条直接消失。后来发现是转录代码时出现了两处错误。
错误点分析
- CSS语法错误:所有CSS规则块结尾多写了分号(比如
body { height: 3000px; };),多余的分号会导致CSS解析异常,进而触发浏览器的溢出提示。 - 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
相关产品推荐
相关产品推荐

