Przegląd
Użytkownicy oczekują natychmiastowej reakcji wizualnej podczas interakcji z elementami interfejsu, takimi jak karuzela czy galeria. Tradycyjne przewijanie z przyciąganiem zapewnia informacje zwrotne dopiero po zakończeniu gestu przewijania i ustabilizowaniu się elementu. Dzięki zdarzeniom przewijania z przyciąganiem, a konkretnie scrollsnapchanging, możesz przekazywać informacje zwrotne w czasie rzeczywistym podczas gestu przewijania, wyróżniając oczekujący cel przyciągania, zanim użytkownik zwolni dotyk lub mysz.
Implementacja
1. Posłuchaj: scrollsnapchanging
Dołącz do kontenera przewijania detektor zdarzeń dla zdarzenia scrollsnapchanging. To zdarzenie jest wywoływane, gdy przeglądarka określi, że prawdopodobnie zostanie wybrany nowy cel przyciągania.
const container = document.querySelector('#gallery');
const thumbnails = document.querySelectorAll('.thumbnail');
const items = document.querySelectorAll('.gallery-item');
container.addEventListener('scrollsnapchanging', (event) => {
// Highlight pending snap target during scroll for real-time feedback.
const pendingTarget = event.snapTargetInline;
const index = [...items].indexOf(pendingTarget);
if (index === -1 || !thumbnails[index]) return;
// Use lightweight class toggle to avoid layout thrashing during rapid events.
// Note: aria-current is NOT toggled here. It tracks the settled "current"
// item, which is updated in the scrollsnapchange handler below.
thumbnails.forEach((thumb) => thumb.classList.remove('pending'));
thumbnails[index].classList.add('pending');
});
W tym przykładzie używamy właściwości snapTargetInline, ponieważ galeria przewija się w poziomie. Jeśli kontener przewijania przewija się w pionie, użyj snapTargetBlock.
2. Posłuchaj: scrollsnapchange
Aby sfinalizować stan po zakończeniu gestu przewijania i faktycznym przyciągnięciu elementu, nasłuchuj zdarzenia scrollsnapchange. Jest to wymagane do ustalenia ostatecznego stanu aktywności.
container.addEventListener('scrollsnapchange', (event) => {
// Promote pending state to active on scroll completion.
const snappedTarget = event.snapTargetInline;
const index = [...items].indexOf(snappedTarget);
if (index === -1 || !thumbnails[index]) return;
// Establish final active state and clean up pending.
thumbnails.forEach((thumb) => {
thumb.classList.remove('pending', 'active');
thumb.removeAttribute('aria-current');
});
thumbnails[index].classList.add('active');
thumbnails[index].setAttribute('aria-current', 'true');
});
3. Stan początkowy synchronizacji
Po wczytaniu strony przeglądarka może przywrócić pozycję przewijania (np. przez przejście do historii lub link do kotwicy). Zdarzenia scrollsnapchange i scroll nie będą wywoływane automatycznie. Uruchom jednorazowe sprawdzenie geometryczne, aby zsynchronizować interfejs z początkową pozycją przewijania.
// Note: For item.offsetLeft to be relative to the container,
// the container MUST be the offsetParent (e.g., `position: relative`).
const findClosestItemIndex = () => {
// Center-distance assumes scroll-snap-align: center on items.
// For start-aligned snap, compare scrollLeft to item.offsetLeft directly.
const containerCenter = container.scrollLeft + container.clientWidth / 2;
let closestIndex = 0;
let minDistance = Infinity;
items.forEach((item, index) => {
const itemCenter = item.offsetLeft + item.offsetWidth / 2;
const distance = Math.abs(containerCenter - itemCenter);
if (distance < minDistance) {
minDistance = distance;
closestIndex = index;
}
});
return closestIndex;
};
const initActiveItem = () => {
const closestIndex = findClosestItemIndex();
if (!thumbnails[closestIndex]) return;
thumbnails.forEach((thumb) => {
thumb.classList.remove('pending', 'active');
thumb.removeAttribute('aria-current');
});
thumbnails[closestIndex].classList.add('active');
thumbnails[closestIndex].setAttribute('aria-current', 'true');
};
if (document.readyState === 'complete') {
initActiveItem();
} else {
window.addEventListener('load', initActiveItem, { once: true });
}
Strategie zastępcze
W przypadku przeglądarek, które nie obsługują scrollsnapchanging, interfejs domyślnie nie będzie przekazywać informacji zwrotnych podczas gestu przewijania, a połączony interfejs będzie się desynchronizować z treścią.
OBOWIĄZKOWO: podaj kreację zastępczą dla przeglądarek, które nie obsługują tej funkcji, w przeciwnym razie połączony interfejs użytkownika nie będzie zsynchronizowany z treścią.
ZALECANE: symuluj działanie scrollsnapchanging w czasie rzeczywistym za pomocą detektora zdarzeń scroll połączonego z requestAnimationFrame i obliczeniami odległości geometrycznej, aby określić najbliższy cel przyciągania, gdy użytkownik aktywnie przewija stronę.
if ('onscrollsnapchanging' in Element.prototype) {
// Use native scroll snap events
} else {
// Fallback: use scroll + requestAnimationFrame for eager feedback
// (assumes the same container, thumbnails, items defined in step 1)
let scrollTimeout;
let rafId = null;
const promotePendingToActive = () => {
const closestIndex = findClosestItemIndex();
if (!thumbnails[closestIndex]) return;
thumbnails.forEach((thumb) => {
thumb.classList.remove('pending', 'active');
thumb.removeAttribute('aria-current');
});
thumbnails[closestIndex].classList.add('active');
thumbnails[closestIndex].setAttribute('aria-current', 'true');
};
container.addEventListener('scroll', () => {
if (rafId) return;
rafId = requestAnimationFrame(() => {
rafId = null;
const closestIndex = findClosestItemIndex();
if (!thumbnails[closestIndex]) return;
// DO NOT forget to clean up stale pending classes
thumbnails.forEach((thumb) => thumb.classList.remove('pending'));
thumbnails[closestIndex].classList.add('pending');
});
// Debounce fallback for browsers that don't support scrollend
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(promotePendingToActive, 100);
}, { passive: true });
// Fallback: use Baseline `scrollend` event to promote pending to active cleanly where supported
container.addEventListener('scrollend', () => {
clearTimeout(scrollTimeout);
promotePendingToActive();
});
}
Geometryczna kreacja zastępcza scroll + requestAnimationFrame dokładnie naśladuje działanie natywnego przewidywania przyciągania, w tym prawidłową obsługę automatycznego przewijania. Funkcje takie jak scrollIntoView naturalnie wywołują zdarzenia scroll podczas wykonywania, więc interfejs będzie płynnie synchronizowany podczas animacji przewijania bez konieczności stosowania dodatkowej logiki niestandardowej.