0

为了允许在 a 内无限滚动<div>,我'scroll'向它添加了一个事件。当第一个孩子在视口中时,我将最后一个孩子放在前面,反之亦然。

在我引入之前,我已经让它完美地工作了scroll-snap-align。在这里,我设置了一个示例,其中一个轮播具有滚动捕捉功能,而另一个则没有。

const scrollInfo = (parent) => {
    let viewWidth = parseInt(getComputedStyle(parent).width),
        realWidth = parent.scrollWidth - viewWidth,
        currentChild = Math.floor((parent.scrollLeft + viewWidth / 3) / viewWidth);
    return {
        current: currentChild,
        view: viewWidth
    };
};

let carousels = [infiniteCarousel1, infiniteCarousel2]

carousels.forEach(carousel => {
carousel.onscroll = () => {
    let info = scrollInfo(carousel),
        scroll = carousel.scrollLeft,
        len = carousel.children.length - 1;
    if (info.current <= 0) {
        carousel.scrollLeft = scroll + info.view;
        carousel.prepend(carousel.children[len]);
    } else if (info.current >= len) {
        carousel.scrollLeft = scroll - info.view;
        carousel.append(carousel.children[0]);
    }
};

window.addEventListener("DOMContentLoaded", () => {
    setTimeout(() => {
        carousel.scrollTo({ left: scrollInfo(carousel).view });
    }, 1000);
})
})
* {
    box-sizing: border-box;
}

.carousel {
    display: flex;
    overflow-x: scroll;
    width: 100%;
    height: 100px;
}

.carousel > div {
    display: inherit;
    justify-content: center;
    align-items: center;
    min-width: 100%;
    height: 100%;
    border: 2px solid;
    scroll-snap-align: center;
}

#infiniteCarousel1 {
    scroll-snap-type: x mandatory;
}
<h2>Scroll Snap</h2>
<div id="infiniteCarousel1" class="carousel">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
</div>

<h2>No Scroll Snap</h2>
<div id="infiniteCarousel2" class="carousel">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
</div>

CodePen中的相同示例。

4

1 回答 1

0

我会告诉你我过去使用的一个技巧。将最后一张幻灯片的额外幻灯片添加到开头,将第一张幻灯片的额外幻灯片添加到末尾。Then when the selected slide its either of those 2. Scroll to position of the original without animation. 让我知道你需要更多帮助。

于 2022-02-12T06:48:55.593 回答