Прокрутка локомотива получить положение элементов - PullRequest
1 голос
/ 07 августа 2020

Я использую Locomotive Scroll для эффекта плавной прокрутки.

Мне нужно изменить цвет фона и цвет всего HTML при достижении определенного участка. В настоящий момент я использую событие вызова на локомотиве, чтобы добавить настраиваемую функцию с именем updateBg, и когда она вызывается, я меняю фон и цвет оболочки. область просмотра, и я переворачиваю прокрутку, это не изменит цвета.

Пример: если я прокручиваю до второго раздела вступления (И первое вступление находится в области просмотра), он изменится на черный фон. Но если я прокручу вверх, он не изменится на белый фон, поскольку секция не выходила из области просмотра, а последний вызов был с черным фоном.

Вы должны полностью пройти через раздел, чтобы иметь возможность чтобы перевернуть цвета.

const initLocomotiveScroll = () => {
  const wrapper = document.querySelector('.wrapper')

  const locoScroll = new LocomotiveScroll({
    el: document.querySelector('[data-scroll-container]'),
    smooth: true
  })

  locoScroll.on('call', (func, dir, obj) => {
    const {
      el
    } = obj

    if ('updateBg' === func) {
      const bg = el.getAttribute('data-bg')
      const color = el.getAttribute('data-color')

      if (dir === 'enter') {
        wrapper.style.backgroundColor = bg
        wrapper.style.color = color
      }
    }
  })
}

setTimeout(() => {
  initLocomotiveScroll()
}, 1000);
/* ------------------------------------------------------------ *\
    Base
\* ------------------------------------------------------------ */

html {
  background: #fff;
  font-size: 16px;
  font-weight: 500;
  line-height: 1.4;
  color: #000;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  margin-bottom: 1rem;
}

h1 {
  margin-bottom: 20px;
  font-size: 50px;
  font-weight: 800;
  line-height: 1.44;
}

h2 {
  font-size: 36px;
  line-height: 1.1667;
}

h3 {
  font-size: 24px;
  font-weight: 800;
}

h4 {
  font-size: 18px;
  font-weight: 600;
}

h5 {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 600;
  text-transform: uppercase;
}

h6 {
  font-size: 14px;
}

p {
  margin-bottom: 1rem;
  &:last-child {
    margin-bottom: 0;
  }
}

.text-large {
  font-size: 24px;
  line-height: 1.7;
}


/* ------------------------------------------------------------ *\
    Wrapper
\* ------------------------------------------------------------ */

.wrapper {
  overflow: hidden;
  min-height: 100vh;
  padding-top: 90px;
  background: #fff;
  color: #000;
  backface-visibility: hidden;
  transition: background-color .4s ease-in, color .4s ease-in;
  will-change: background-color, color;
}


/* ------------------------------------------------------------ *\
    Container
\* ------------------------------------------------------------ */

.container {
  width: 100%;
  max-width: 1156px;
  padding: 0 60px;
  margin: 0 auto;
}


/* ------------------------------------------------------------ *\
    Fullsize Image
\* ------------------------------------------------------------ */

.fullsize-image {
  position: relative;
  display: block;
  background-position: 50% 50%;
  background-size: cover;
  background-repeat: no-repeat;
  &>img {
    position: absolute;
    top: 0;
    left: 0;
    height: 1px;
    width: 1px;
    opacity: 0;
  }
}


/* ------------------------------------------------------------ *\
    Intro
\* ------------------------------------------------------------ */

.intro {
  position: relative;
  padding: 105px 0;
  &__content {
    max-width: 800px;
  }
  &__entry {
    max-width: 520px;
    margin-bottom: 15px;
  }
}


/* ------------------------------------------------------------ *\
    Section Gutter
\* ------------------------------------------------------------ */

.section-gutter {
  padding: 50px 0;
}
<script src="https://cdn.jsdelivr.net/npm/locomotive-scroll@3.5.4/dist/locomotive-scroll.min.js"></script>
<div class="wrapper" data-scroll-container>
  <main class="main">
    <div data-scroll-section>
      <section class="intro" data-scroll data-bg="#ffffff" data-color="#000000" data-scroll-repeat="true" data-scroll-call="updateBg">
        <div class="container">
          <div class="intro__content">
            <h5 class="intro__subtitle">
              <span>Lorem ipsum dolor.</span>
            </h5>

            <h2 class="intro__title">If I scroll to the second intro section (AND the first intro is in the viewport) it will change to a black background. But if I scroll up it will not change to a white background as the section did not get out from the viewport and the last
              call was with a black background.</h2>

            <p>You have to completely pass through a section to be able to reverse back the colors.</p>
          </div>
        </div>
      </section>
    </div>

    <div data-scroll-section>
      <div class="section-gutter">
        <div class="container">
          <h1>This is section just for gutters</h1>
        </div>
      </div>
    </div>

    <div data-scroll-section>
      <section class="intro" data-scroll data-bg="#000000" data-color="#ffffff" data-scroll-repeat="true" data-scroll-call="updateBg">
        <div class="container">
          <div class="intro__content">
            <h5 class="intro__subtitle">
              <span>Lorem ipsum dolor.</span>
            </h5>

            <h1 class="intro__title">There is some kind of bug for changing the colors of the next sections, but they are not part of the main problem. On real project, it is working correctly.</h1>
          </div>
        </div>
      </section>
    </div>

    <div data-scroll-section>
      <div class="section-gutter">
        <div class="container">
          <h1>This is section just for gutters</h1>
        </div>
      </div>
    </div>

    <div data-scroll-section>
      <section class="intro" data-scroll data-bg="#ffffff" data-color="#000000" data-scroll-repeat="true" data-scroll-call="updateBg">
        <div class="container">
          <div class="intro__content">
            <h5 class="intro__subtitle">
              <span>Lorem ipsum dolor.</span>
            </h5>

            <h1 class="intro__title">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, asperiores?</h1>
          </div>
        </div>
      </section>
    </div>

    <div data-scroll-section>
      <div class="section-gutter">
        <div class="container">
          <h1>This is section just for gutters</h1>
        </div>
      </div>
    </div>

    <div data-scroll-section>
      <section class="intro" data-scroll data-bg="#000000" data-color="#ffffff" data-scroll-repeat="true" data-scroll-call="updateBg">
        <div class="container">
          <div class="intro__content">
            <h5 class="intro__subtitle">
              <span>Lorem ipsum dolor.</span>
            </h5>

            <h1 class="intro__title">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, asperiores?</h1>
          </div>
        </div>
      </section>
    </div>
  </main>
</div>

Я думаю, единственный подход, который будет работать, - это найти верхнюю часть смещения секций и установить цвета на основе смещения верхней части секции и прокрутки локомотива дельта. Проблема в том, что единственное место, где я могу взять их смещения, - это когда запускается событие вызова.

Как я могу взять все вершины смещения секций под нагрузкой? Может кто-нибудь придумать другой обходной путь?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...