fix(carousel): change the way slide position is computed (#1235)

This commit is contained in:
Alessandro
2023-03-13 15:56:00 +01:00
committed by GitHub
parent df25f8617b
commit 7bf0f647b3

View File

@@ -344,7 +344,7 @@ export default class SlCarousel extends ShoelaceElement {
* @param behavior - The behavior used for scrolling.
*/
goToSlide(index: number, behavior: ScrollBehavior = 'smooth') {
const { slidesPerPage, loop } = this;
const { slidesPerPage, loop, scrollContainer } = this;
const slides = this.getSlides();
const slidesWithClones = this.getSlides({ excludeClones: false });
@@ -358,9 +358,12 @@ export default class SlCarousel extends ShoelaceElement {
const nextSlideIndex = clamp(index + (loop ? slidesPerPage : 0), 0, slidesWithClones.length - 1);
const nextSlide = slidesWithClones[nextSlideIndex];
this.scrollContainer.scrollTo({
left: nextSlide.offsetLeft,
top: nextSlide.offsetTop,
const scrollContainerRect = scrollContainer.getBoundingClientRect();
const nextSlideRect = nextSlide.getBoundingClientRect();
scrollContainer.scrollTo({
left: nextSlideRect.left - scrollContainerRect.left + scrollContainer.scrollLeft,
top: nextSlideRect.top - scrollContainerRect.top + scrollContainer.scrollTop,
behavior: prefersReducedMotion() ? 'auto' : behavior
});
}