Идея состоит в том, чтобы использовать обратный вызов изменения и рассчитать приращение для прокрутки окна. Это приращение равно прогрессу, умноженному на расстояние, которое мы хотим прокрутить.
Тем не менее, я предполагаю, что вы хотите иметь возможность перемещаться по нескольким разделам, используя только кнопки назад и вперед . Поскольку пользователь также может вручную прокручивать к различным разделам, вам нужен способ определить, какой раздел отображается в данный момент, и программно перейти к предыдущему / следующему разделу.
Следующий код делает это, поддерживая список секций, упорядоченных по их левым координатам.
В этом примере я рассматриваю текущий раздел как раздел, охватывающий центральную линию экрана.
import animate from "https://cdn.jsdelivr.net/npm/animateplus@2/animateplus.js"
const previousPage = document.querySelector("button:nth-of-type(1)")
const nextPage = document.querySelector("button:nth-of-type(2)")
const root = document.scrollingElement;
const sections = Array.from(document.querySelectorAll("section")).sort((s1, s2) => {
return s1.getBoundingClientRect().left - s2.getBoundingClientRect().left;
});
// get the section that spans the centerline
const getSectionInView = () => {
const halfWdidth = window.innerWidth / 2;
const index = sections.findIndex(s =>
s.getBoundingClientRect().left <= halfWdidth &&
s.getBoundingClientRect().right > halfWdidth
);
return index;
};
// find the next or previous section in the list
const getNextSection = (dir) => {
const sectionInViewIndex = getSectionInView();
const nextIndex = sectionInViewIndex + dir;
const numSections = sections.length;
const nextSectionIndex = nextIndex < 0 || nextIndex >= numSections ? sectionInViewIndex : nextIndex;
return sections[nextSectionIndex];
};
// animation function
const animateScroll = (dir) => {
const from = root.scrollLeft;
const { left } = getNextSection(dir).getBoundingClientRect();
return progress => root.scrollLeft = from + progress * left
};
previousPage.addEventListener("click", () => {
animate({
easing: "out-quintic",
change: animateScroll(-1)
});
});
nextPage.addEventListener("click", () => {
animate({
easing: "out-quintic",
change: animateScroll(1)
});
});
Вот CodePen
Для этого вам нужно удалить scroll-snap-align: center;
из стиля section
или установить его на none
, так как он конфликтует с анимацией.