1

Подскажите, пожалуйста, как при скроллинге активировать анимацию в тот момент, когда видимым станет блок .parallax, и в пределах одного только этого блока? Сейчас анимация происходит при скроллинге всего body. Благодарю!

$(function() {
  $('.parallax').animate({
    scrollTop: $(document).height()
  }, 1000);

  $(window).scroll(function() {
    $('span').css('font-size', Math.round($(window).scrollTop() / 5) + 'px');
  });
})
* {
  margin: 0;
}

.header,
.footer,
.parallax {
  height: 1000px;
}

.header,
.footer {
  background-color: pink;
}

.parallax {
  background-color: beige;
}

span {
  text-align: center;
  font-size: 0px;
  position: fixed;
  top: 50%;
  left: 0;
  right: 0;
  height: 2px;
  line-height: 2px;
  margin-top: -1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header"></div>
<div class="parallax"><span>Parallax</span></div>
<div class="footer"></div>

1
  • 1
    Сейчас не могу нормально ознакомиться с кодом и потыкать, то тебе нужно, как мне кажется, вот сюда посмотреть. 5 фев 2020 в 9:59

1 ответ 1

1

Вот решение. Спасибо @рони за помощь.

$(function() {
  var parallax = document.querySelector('.parallax');

  $(window).scroll(function() {
    var {
      top,
      bottom
    } = parallax.getBoundingClientRect();
    var size = 0;
    if (top < 0 && bottom > window.innerHeight) size = Math.round(-top / (parallax.scrollHeight - window.innerHeight) * 120);
    if (bottom < window.innerHeight) size = 120;
    $('span').css('font-size', `${size}px`);
  });
})
html,
body {
  margin: 0;
  padding: 0;
}

.header,
.footer {
  position: relative;
  z-index: 1;
  background-color: pink;
  height: 1000px;
}

.parallax {
  position: relative;
  z-index: 0;
  background-color: beige;
  height: 1000px;
}

span {
  text-align: center;
  font-size: 0px;
  position: fixed;
  top: 50%;
  left: 0;
  right: 0;
  height: 2px;
  line-height: 2px;
  margin-top: -1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header"></div>
<div class="parallax"><span>Parallax</span></div>
<div class="footer"></div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.