Изменить тему-цвет при прокрутке

#javascript #html #jquery #css

#javascript #HTML #jquery #css

Вопрос:

Я пытаюсь реализовать решение, в котором при прокрутке различных разделов моего сайта, отмеченных

 <section>
</section>
  

HTML-теги,:

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

Изменения, скажем, например, у вас было 3 раздела, первый имел черный фон, второй белый, а третий красный — при прокрутке каждого раздела цвет темы менялся соответствующим образом. Пока у меня есть:

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

Однако я не уверен, куда идти дальше. Я надеюсь, что вы, ребята, сможете мне помочь, спасибо.

Комментарии:

1. вы пробовали при наведении курсора мыши?

2. Нет, это для мобильного сайта.

Ответ №1:

Приведенный ниже код делает свое дело:

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>
  

и 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');
});