简体   繁体   English

如果滚动为 100 像素,则将背景变为红色。 (纯 JavaScript)

[英]If scroll is 100px then turn background into red. (Pure JavaScript)

I am having trouble with scroll using if statements.我在使用 if 语句滚动时遇到问题。

How can I fix it and any helpful tips will be much appreciated.我该如何解决它以及任何有用的提示将不胜感激。

 if (window.scrollY == '100px') { document.body.style.backgroundColor = "red"; }
 div { position: absolute; top: 200%; font-size: 5vw; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <script src="script.js"></script> <div> hi </div> </body> </html>

You need to listen on scroll event first.您需要先监听scroll事件。 window.scrollY value is integer. window.scrollY值为整数。

 window.addEventListener("scroll", function() { if (window.scrollY >= 100) { document.body.style.backgroundColor = "red"; } });
 div { position: absolute; top: 200%; font-size: 5vw; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <script src="script.js"></script> <div> hi </div> </body> </html>

The condition needs to be >= 100 , and you need to listen to the scroll event of the window.条件需要>= 100 ,并且需要监听窗口的scroll事件。

Here is a working snippet:这是一个工作片段:

 window.addEventListener("scroll", function() { if (window.scrollY >= 100) { document.body.style.backgroundColor = "red"; } });
 .container { position: absolute; top: 200%; font-size: 2rem; }
 <div class="container">hi</div>

You can do it as follows -您可以按照以下方式进行 -

 window.addEventListener("scroll", function() { if (window.scrollY >= 100) { document.body.style.backgroundColor = "red"; }else{ document.body.style.backgroundColor = "white"; } });
 *{ transition-duration: 1s; } div { position: absolute; top: 200%; font-size: 5vw; }
 <div> hi </div>

In your code, you had written the condition to be window.scrollY == 100px , so it was not working.在您的代码中,您已将条件编写为window.scrollY == 100px ,因此它不起作用。 But once you modify the condition, the code will work as expected.但是一旦你修改了条件,代码就会按预期工作。

Also, the else statement or transition effect are not needed, just added them for nice effect.此外,不需要else语句或过渡效果,只需添加它们以获得良好的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM