【问题标题】:Infinite scroll conflicts with scroll-snap-align CSS property无限滚动与 scroll-snap-align CSS 属性冲突
【发布时间】:2022-02-12 14:48:55
【问题描述】:

为了允许在<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 中的相同示例。

【问题讨论】:

    标签: javascript css carousel scroll-snap


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 2021-11-13
      • 2017-12-06
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多