【JS】背景画像のパララックス

content......

① CSS

.class {
position: relative;
background-size: 110%;
background-position: center center;
background-repeat: no-repeat;
overflow: hidden;
will-change: background-position;
}

② JS

document.addEventListener("scroll", function () {

const section = document.querySelector(".voice");
if (!section) return;

const rect = section.getBoundingClientRect();
const windowHeight = window.innerHeight;

if (rect.top < windowHeight && rect.bottom > 0) {

const sectionCenter = rect.top + rect.height / 2;
const windowCenter = windowHeight / 2;

const distance = sectionCenter - windowCenter;

const move = distance * -0.1;

section.style.backgroundPosition = `center calc(50% + ${move}px)`;
}

});

コメント

タイトルとURLをコピーしました