简体   繁体   中英

Change background color on specifiied scroll position

I'm experimenting with something new in Javascript. I would like to change the background color of an item when the scrollY position has reached a specific value; 80 in this case. However, it's not working. Is there something wrong with the logic?

window.addEventListener("scroll", function (event){
   var scroll = this.scrollY;
   if scroll.value === '80' {
       document.getElementById="Gegevens".style.background-color="lightblue" } else {}
}) 

There are a number of errors in your code:

  • You need brackets around your if condition
  • You already have the scroll value so no need for scroll.value
  • The scroll position will rarely be exactly 80 so you should do greater than or equal to 80
  • 80 is returned as a number, not a string (though you can compare it as a string, it doesn't make much sense to)
  • The syntax for getElementById needs brackets not an equals sign
  • You need to use camelCase for background-color
  • Something I just learnt, you don't need to pass event as a parameter when using this (not an error but interesting either way)

This is how it should be:

window.addEventListener("scroll", function(event) {
   const scroll = this.scrollY;
   if (scroll >= 80)
       document.getElementById("Gegevens").style.backgroundColor="lightblue"
}) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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