简体   繁体   English

如何在Javascript中使用滚动事件(无Jquery)

[英]How to use the scroll event in Javascript (NO Jquery)

So HERE is the code. 所以这里是代码。 I simple want to change the color of the h1 heading when the scroll is 1000px from top. 我简单地想在滚动距顶部1000px时更改h1标题的颜色。 I would like to use purely javascript for this purpose.Please try and ignore how poorly the code has been written. 我想仅使用JavaScript来实现此目的。请尝试忽略代码编写的糟糕程度。 Any suggestion would be more than welcome. 任何建议都将受到欢迎。 Thank you for you time. 谢谢您的时间。

 <html> <head> <title> scroll </title> <!-- CSS !--> <style> .redbox { background-color: red; position: absolute; top: 10px; height: 90px; width: 100px; } .reveal { position: fixed; top:450px; transition: width 2s; display: block; } </style> </head> <!-- HTML !--> <body> <div class='redbox' id='red'> , </div> <h1 class='reveal' id='demo'> The comes up on 1000 scroll! </h1> <h1 style='position: absolute;top: 1900px;'> END </h1> <!-- JS !--> <script> var top = window.pageYOffset || document.documentElement.scrollTop if (top == 1000) { document.getElementById('demo').style.color = 'red'} </script> </body> </html> 

You could check the current scroll offset using an event handler: 您可以使用事件处理程序检查当前滚动偏移量:

document.body.addEventListener('scroll', function() {

    if(window.scrollY > 499) {
        document.getElementById('myDiv').classList.add('appear'); // or whatever...
    }

});

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

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