Вы можете использовать наблюдатель пересечения , чтобы обнаружить, когда достаточное количество элемента .pink
находится внутри области просмотра, коснуться элемента .blue
:
const body = document.querySelector('body');
const blue = document.querySelector('.blue');
const target = document.querySelector('.pink');
const getHeight = (el) => el.getBoundingClientRect().height;
// get the threshold in which enough of the pink elment would be inside the viewport to touch the blue element
const threshold = (window.innerHeight - getHeight(blue)) / getHeight(target);
const options = {
rootMargin: '0px',
threshold
};
let prevRatio = 0;
const handleIntersect = (entries, observer) => {
entries.forEach(function(entry) {
// if going up (above the previous threshold & above the threshold
if (entry.intersectionRatio >= threshold && entry.intersectionRatio > prevRatio) {
body.classList.add('body--intersected');
} else {
body.classList.remove('body--intersected');
}
prevRatio = entry.intersectionRatio;
});
}
const observer = new IntersectionObserver(handleIntersect, options);
observer.observe(target);
body {
margin: 0;
background: lightblue;
}
.body--intersected {
background: pink;
}
.blue-container {
height: 70vh;
}
.blue {
height: 40vh;
position: sticky;
width: 70%;
top: 0;
background: blue;
margin: auto;
}
.pink {
height: 500px;
position: relative;
width: 70%;
margin-right: auto;
margin-left: auto;
background: pink;
text-align: center;
}
<div class='blue-container'>
<div class='blue'></div>
</div>
<div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div>