【问题标题】:Swiper JS How zoom-in or zoom-out image several times on click?Swiper JS 如何在点击时多次放大或缩小图像?
【发布时间】:2022-12-05 16:32:34
【问题描述】:

我想在 swiper js 的图库中制作两个按钮“-”和“+”。如何在每次点击时增加/减少比例?我需要保持在图像中移动的能力!

现在我的 React 应用程序中有这段代码:

const maxScale = 5;

const [scale, setScale] = useState(1);

const handleMagnifier = (type) => {
  if (scale < maxScale && type === 'in') {
    setScale(scale + 1);
    swiperRef.current?.zoom.in();
  } else if (scale <= maxScale && type === 'out') {
    setScale(scale - 1);
    scale === 1 ? swiperRef.current?.zoom.out() : swiperRef.current?.zoom.in();
  }
};

使成为


         <IconButton onClick={handleMagnifier('out')}>
            <Icon name='zoom-out' />
         </IconButton>
         <IconButton onClick={handleMagnifier('in')}>
            <Icon name='zoom-in' />
         </IconButton>

         <Swiper
          slides={slides}
          SwiperOptions={{
            mousewheel: true,
            freeMode: true,
            onSwiper,
            slidesPerView: 1,
            keyboard: {
              enabled: true,
            },
            preloadImages: false,
            lazy: {
              checkInView: true,
              loadPrevNext: true,
            },
            observer: true,
            onSlideChange,
            onAfterInit: (): void => setInited(true), // Prevent flickering
            thumbs: {
              swiper: thumbsSwiper,
              autoScrollOffset: 0,
            },
            initialSlide: initialIndex,
            zoom: {
              maxRatio: scale,
              minRatio: 1,
            },
          }}
          {...(items.length > 1 && navigationProps)}
        />

但它不起作用。

我试图搜索示例,阅读文档,但没有决定。

【问题讨论】:

    标签: reactjs swiper.js


    【解决方案1】:

    您可以使用 Swiper 实例的缩放属性来放大和缩小图像。以下是如何实现此目标的示例:

    var mySwiper = new Swiper('.swiper-container', {
      // your options here
    });
    
    document.getElementById('zoom-in-button').addEventListener('click', function() {
      mySwiper.scale += 0.1;
    });
    
    document.getElementById('zoom-out-button').addEventListener('click', function() {
      mySwiper.scale -= 0.1;
    });
    

    此代码创建一个 Swiper 实例并将其分配给 mySwiper 变量。然后,它将点击事件侦听器添加到具有放大按钮和缩小按钮 ID 的元素。单击这些按钮时,mySwiper 实例的 scale 属性将分别递增或递减 0.1。这会导致图像放大或缩小。

    请记住,这只是一个示例,您可能需要对其进行修改以满足您的特定需求。例如,您可能想要添加一些检查以确保缩放属性保持在特定范围内,或者您可能想要更改缩放属性在每次单击时更改的量。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 2011-06-29
    • 2012-02-19
    • 1970-01-01
    • 2013-12-11
    • 2013-05-23
    • 2013-12-18
    相关资源
    最近更新 更多