2 деления с фиксированными изображениями, которые реагируют на прокрутку - PullRequest
0 голосов
/ 02 мая 2018

Я пытаюсь создать анимацию прокрутки с 2 делениями и 2 изображениями. Из-за отсутствия лучшего объяснения (как вы могли догадаться из названия) я сделал быструю анимацию , демонстрирующую то, чего я пытаюсь достичь.

здесь - это версия, размещенная мной ранее. Я попытался создать эффект с помощью параллакс-прокрутки, но это не совсем то, что я хочу. Это развертывание Zeit Now, так что вы можете добавить / _ src к URL и взглянуть на исходный код.

Теперь я не уверен, является ли это даже правильным способом создания анимации, и, честно говоря, я бы не знал другого способа, которым я мог бы подойти к этому. Поэтому я не прошу полноценный ответ без каких-либо недостатков (хотя это было бы очень важно), а скорее подтолкнул в правильном направлении.

1 Ответ

0 голосов
/ 02 мая 2018

Сделано это быстро, поэтому могут возникнуть некоторые проблемы, я попытался сделать переменные как-то общими, чтобы вы могли поиграть с вещами (отметьте это fiddle )

const body = document.body,
  html = document.documentElement;

const targetImg = document.querySelector('.second');
// our image's initial height
const imgHeight = targetImg.clientHeight;
// the final value for image height (at scroll end)
const imgTargetHeight = 0;
// total height of our document
const totalHeight = Math.max(body.scrollHeight, body.offsetHeight,
  html.clientHeight, html.scrollHeight, html.offsetHeight);
// visible window height
const windowHeight = window.innerHeight;
// starting scroll position we want to start calculations from (at this point and before, our image's height should equal its initial height 'imgHeight')
const fromScroll = 0;
// final scroll position (at this point and after, our image's height should equal 'imgTargetHeight')
const toScroll = totalHeight - windowHeight;

window.addEventListener('scroll', function() {
  // get current scroll position, these multiple ORs are just to account for browser inconsistencies.
  let scrollPos = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;

  // force the scroll position value used in our calculation to be between 'fromScroll` and 'toScroll'
  // In this example this won't have any 
  // effect since fromScroll is 0 and toScroll is the final possible scroll position 'totalHeight - windowHeight',
  // but they don't have to be, try setting fromScroll = 100 and toScroll = totalHeight - windowHeight - 100  for example to see the difference.
  // the next line is just a shorthand for:
  // if (scrollPos <= fromScroll) {
  //   scrollPos = fromScroll;
  // } else if (scrollPos >= toScroll) {
  //   scrollPos = toScroll;
  // } else {
  //   scrollPos = scrollPos;
  // }
  scrollPos = scrollPos <= fromScroll ? fromScroll : (scrollPos >= toScroll ? toScroll : scrollPos);

  // our main calculation, how much should we add to the initial image height at our current scroll position.
  const value = (imgTargetHeight - imgHeight) * (scrollPos - fromScroll) / (toScroll - fromScroll);

  targetImg.style.height = imgHeight + value + "px";
});
.container {
  height: 200vh;
}

.img-container {
  position: fixed;
  width: 100vw;
  height: 100vh;
  text-align: center;
  background: white;
  overflow: hidden;
}

.second {
  background: tomato;
}

img {
  position: absolute;
  left: 50vw;
  top: 50vh;
  transform: translate(-50%, -50%);
}
<div class="container">
  <div class="img-container first">
    <img src="https://fixedscrollingtest-takidbrplw.now.sh/luigi.png" alt="">
  </div>
  <div class="img-container second">
    <img src="https://fixedscrollingtest-takidbrplw.now.sh/mario.png" alt="">

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