首页 > 解决方案 > 这种循环行为在 Swiper 中是否可行?

问题描述

假设我们有以下滑动幻灯片:

默认情况下,滑块将显示第一组 (1, 2, 3)

[1 2 3] 4 5 6 7

如果单击右箭头按钮,它将转到第 2 页:

1 2 3 [4 5 6] 7

下一个将只显示一个

1 2 3 4 5 6 [7 _ _]

下一次我们按下右箭头按钮将循环到第一页

[1 2 3] 4 5 6 7

我想要以下行为,而不是这种行为:

最后一页应显示以下不带空格的元素:

1 2 3 4 [5 6 7]

然后保持下一个将再次成为第一页

如果从最后一页循环回来(单击左箭头按钮),行为应该是这样的:

1 2 3 4 [5 6 7]> 1 [2 3 4] 5 6 7>[1 2 3] 4 5 6 7

这可能吗?如何?

标签: javascriptswiper

解决方案


所以基本上,默认情况下这种行为是不可能的,所以我(我的团队)添加了一些自定义逻辑来实现它:

我将只发布一些代码,省略细节。另请注意,我将它与 React 和 TypeScript 一起使用

progressMode需要是'freescroll'

public slideTimes = (times: number, direction: 'right' | 'left') => {
  const swiper = this.swiperRef.current && this.swiperRef.current.swiper;
  if (!swiper) return null;
  swiper.loopFix();
  swiper._clientLeft = swiper.$wrapperEl[0].clientLeft;
  return direction === 'right'
    ? swiper.slideTo(swiper.activeIndex + times)
    : swiper.slideTo(swiper.activeIndex - times);
};

protected slideNext = () => {
  if (!this.slideShowRef.current) {
    return;
  }
  const { currentPage } = this.state;
  const { services } = this.props;

  let nextPage = currentPage + 1;
  if (nextPage > Math.ceil(services.length / SLIDES_PER_PAGE)) {
    nextPage = 1;
  }
  this.setState({ currentPage: nextPage, swipping: true }, () => {
    const remainingServicesLastPage = services.length % SLIDES_PER_PAGE;
    if (
      remainingServicesLastPage !== 0 &&
      nextPage === Math.ceil(services.length / SLIDES_PER_PAGE)
    ) {
      return this.slideShowRef.current.slideTimes(remainingServicesLastPage, 'right');
    }
    return this.slideShowRef.current.slideTimes(SLIDES_PER_PAGE, 'right');
  });
};

protected slidePrev = () => {
  if (!this.slideShowRef.current) {
    return;
  }
  const { currentPage } = this.state;
  const { services } = this.props;

  let prevPage = currentPage - 1;
  if (prevPage < 1) {
    prevPage = Math.ceil(services.length / SLIDES_PER_PAGE);
  }
  this.setState({ currentPage: prevPage, swipping: true }, () => {
    const remainingServicesLastPage = services.length % SLIDES_PER_PAGE;
    if (
      remainingServicesLastPage !== 0 &&
      prevPage === Math.ceil(services.length / SLIDES_PER_PAGE) - 1
    ) {
      return this.slideShowRef.current.slideTimes(remainingServicesLastPage, 'left');
    }
    return this.slideShowRef.current.slideTimes(SLIDES_PER_PAGE, 'left');
  });
};

推荐阅读