简体   繁体   中英

Change Theme-Colour on scroll

I am attempting to implement a solution where by as you scroll through various sections of my site, marked by the

<section>
</section>

HTML Tags, the:

<meta name="theme-color" content="#535353">

Changes, say for example you had 3 sections, the first had a Black background, second white, and third red- as you scrolled through each section, the theme-colour changed appropriately. So far I have:

document.querySelector('meta[name="theme-color"]').setAttribute('content',  '#535353');

However I am unsure where to go from here. I hope you guys will be able to help me out, thanks.

Below code does the trick:

css:

section {
  height: 100vh;
  display: block;
}

html:

  <section data-theme-color="red">
    <p>sesction conent</p>
  </section>
  <section data-theme-color="green">
    <p>sesction conent</p>
  </section>
  <section data-theme-color="blue">
    <p>sesction conent</p>
  </section>

and js:

var theme = document.querySelector('meta[name="theme-color"]'),
  getThemeColor = theme.getAttribute('content'),
  sectionElem = document.getElementsByTagName('section'),
  sectionHeight = sectionElem[0].clientHeight,
  sectionLength = sectionElem.length;

// set color on load
window.onload = () => {
  document.body.style.backgroundColor = theme.getAttribute('content');
}

// set color on 'scroll' event
window.addEventListener('scroll', (e) => {
  var offset = window.pageYOffset,
    sectionIndex = parseInt(offset, "10") % sectionLength,
    sectionColor = document.getElementsByTagName('section')[sectionIndex].getAttribute('data-theme-color'),
    setSectionColor = theme.setAttribute('content', sectionColor);

  document.querySelectorAll('section')[sectionIndex].style.backgroundColor = theme.getAttribute('content');
});

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