简体   繁体   中英

Changing background color on scroll with javascript

https://codepen.io/tobiasthaden/pen/OVWKjm


$(window).scroll(function() {
  $('section').each(function(i) {
    if ($(this).position().top <= $(window).scrollTop()) {
      $('body').css('background-color', $(this).attr('data-color'));
    }
  });
});

Looking to replicate this effect using regular old javascript. I don't want to use jQuery!

Any tips?

 const sections = document.querySelectorAll('section') window.addEventListener('scroll', function() { sections.forEach(section => { const distFromTop = document.body.scrollTop + section.getBoundingClientRect().top if (distFromTop < 10) { document.body.style.background = section.dataset.color } }) })
 body { transition: background-color.2s ease; } section { height: 100vh; }
 <section data-color="white"></section> <section data-color="green"></section> <section data-color="purple"></section> <section data-color="yellow"></section> <section data-color="blue"></section> <section data-color="white"></section>

This seems to work well enough!

I would have done it like this.

 const sections = document.querySelectorAll('section') document.addEventListener('scroll', () => { sections.forEach(section => { if(section.getBoundingClientRect().top <= document.body.scrollTop) { document.body.style.background = section.dataset.color } }) })
 body { transition: background-color.2s ease; } section { height: 100vh; }
 <section data-color="white"></section> <section data-color="green"></section> <section data-color="purple"></section> <section data-color="yellow"></section> <section data-color="blue"></section> <section data-color="white"></section>

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