Активировать parallax на видимом блоке
Подскажите, пожалуйста, как при скроллинге активировать анимацию в тот момент, когда видимым станет блок .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 шт):
Автор решения: Sevastopol'
→ Ссылка
Вот решение. Спасибо @рони за помощь.
$(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>