简体   繁体   English

如何使用 vanilla Javascript 在滚动时更改标题的背景颜色

[英]How to change background colour of header on scroll using vanilla Javascript

I'm currently attempting to change the background colour of my header when the user scrolls but it doesn't seem to be working.我目前正在尝试在用户滚动时更改标题的背景颜色,但它似乎不起作用。 I have attached an onscroll attribute to the body tag and created the appropriate function in Javascript to no avail.我已将 onscroll 属性附加到 body 标记并在 Javascript 中创建了适当的函数,但无济于事。 Here is the JSFiddle: https://js fiddle.net/Le7jctz8/这是 JSFiddle: https://js fiddle.net/Le7jctz8/

Solution解决方案

One possibility is to add an event listener to your document body and listen for scroll events and check the Y position of the document as the user scrolls.一种可能性是在您的文档正文中添加一个事件侦听器并侦听滚动事件并在用户滚动时检查文档的 Y 位置。

Code代码

var header = document.getElementById('header');
var oldColor = header.style.backgroundColor;

document.body.addEventListener('scroll', () => {
    let yPosition = document.body.scrollTop;
    if (yPosition > 100) {
        header.style.backgroundColor = "teal";
    }
    else {
        header.style.backgroundColor = oldColor;
    }
})

Here is a JSFiddle for visual clarity.这是一个 JSFiddle 以提高视觉清晰度。

https://jsfiddle.net/5hpr7kos/37/ https://jsfiddle.net/5hpr7kos/37/

I hope this helps.我希望这有帮助。

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

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