微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何阻止 Swiper.JS Thumbs 自动转换?

如何解决如何阻止 Swiper.JS Thumbs 自动转换?

我有一个用 react 制作的 swiper.js 滑块。如果我在 swiper 中有 8 个图像,然后我导航到第 8 个缩略图并单击第 7 个缩略图,它将向上滑动缩略图部分。有没有办法防止这种行为发生?

我想要做的是让它仅在有更多可用的向上或向下滑动时才自动滑动。例如,如果我有 5 个缩略图并且幻灯片 [2,3,4,5,6] 是可见的,如果我选择幻灯片 6,它会移动并显示幻灯片 7 可用,如果我选择幻灯片 2 它会滑过并显示幻灯片 1. 这是我想让它做的唯一动作。该功能在文档中可用吗?

<html>
<h1> Header </h1>
[Google Document Code Goes Here.]
</html>

解决方法

看起来没有办法在不操作数据的情况下实现具有这种行为的缩略图。所以想法是当您更改缩略图时,您需要重新排列数据以显示下一个/上一个缩略图。

export default function App() {
  const [thumbsSwiper,setThumbsSwiper] = useState(null);

  const [data,setData] = useState([
    "https://swiperjs.com/demos/images/nature-1.jpg","https://swiperjs.com/demos/images/nature-2.jpg","https://swiperjs.com/demos/images/nature-3.jpg","https://swiperjs.com/demos/images/nature-4.jpg","https://swiperjs.com/demos/images/nature-5.jpg","https://swiperjs.com/demos/images/nature-6.jpg","https://swiperjs.com/demos/images/nature-7.jpg","https://swiperjs.com/demos/images/nature-8.jpg","https://swiperjs.com/demos/images/nature-9.jpg","https://swiperjs.com/demos/images/nature-10.jpg"
  ]);

  return (
    <>
      <Swiper
        style={{
          "--swiper-navigation-color": "#fff","--swiper-pagination-color": "#fff"
        }}
        loop={false}
        spaceBetween={10}
        navigation={true}
        thumbs={{ swiper: thumbsSwiper }}
        className="mySwiper2"
        onSlideChange={(e) => {
          if (e.realIndex % 3 === 0) {
            // move first element to the end
            const newData = [...data];
            newData.push(newData.shift());
            setData(newData);
            e.slideTo(e.realIndex - 1);
          }
          if (e.realIndex === 0) {
            // move last element to the beginning
            const newData = [...data];
            newData.unshift(newData.pop());
            setData(newData);
            e.slideTo(e.realIndex + 1);
          }
        }}
      >
        {data.map((img) => (
          <SwiperSlide key={img}>
            <img src={img} />
          </SwiperSlide>
        ))}
      </Swiper>
      <Swiper
        onSwiper={setThumbsSwiper}
        loop={false}
        loopedSlides={1}
        spaceBetween={10}
        slidesPerView={4}
        freeMode={false}
        watchSlidesVisibility={true}
        watchSlidesProgress={true}
        className="mySwiper"
      >
        {data.map((img) => (
          <SwiperSlide key={img}>
            <img src={img} />
          </SwiperSlide>
        ))}
      </Swiper>
    </>
  );
}

这是一个codesandbox

这只是一个简单的例子。希望能帮到你。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。