如何在swiper.js中更改滑动方向?

时间:2019-02-08 14:02:09

标签: javascript css reactjs ecmascript-6 swiper

当我将扫掠器旋转90度时,我正努力改变滑动方向。因此,默认情况下,开始时它具有水平方向。单击幻灯片时,我正在旋转“雨刷容器”,使其变为全屏显示。因此,它仍然具有从左向右滑动的方向,但是我需要从上到下更改而无需将参数方向更改为垂直。

const topSwiper = new Swiper(this.DOMTopSwiper.current, {
  spaceBetween: 0,
  observer: true,
  observeParents: true,
  observeSlideChildren: true,
  direction: "vertical",
  navigation: {
    nextEl: ".top-swiper-button-next",
    prevEl: ".top-swiper-button-prev",
  },
  pagination: {
    el: ".zoom-amount-slides",
    type: "fraction",
  },
})

1 个答案:

答案 0 :(得分:4)

销毁先前的Swiper并重新初始化Swiper,以提供方向值。这是doc

演示

let isVertical = true,
  direction = 'vertical';
let swiper = initSwiper(direction);

function initSwiper(direction) {
  return new Swiper('.swiper-container', {
    spaceBetween: 50,
    pagination: {
      el: '.swiper-pagination',
      clickable: true,
    },
    direction: direction
  });

}

function changeDirection() {
  isVertical = !isVertical;
  direction = isVertical ? 'vertical' : 'horizontal';
  let slideIndex = swiper.activeIndex;
  swiper.destroy(true, true);
  swiper = initSwiper(direction);
  swiper.slideTo(slideIndex,0);
}
html, body {
  position: relative;
  height: 100%;
}
body {
  background: #eee;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
  font-size: 14px;
  color:#000;
  margin: 0;
  padding: 0;
}
.swiper-container {
  width: 400px;
  height: 400px;
}
.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;
  /* Center slide text vertically */
  display: -webkit-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
}
<!-- Link Swiper's CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.4.6/css/swiper.min.css">
<!-- Swiper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.4.6/js/swiper.js"></script>
<button onclick='changeDirection()'>Change Direction</button>
<!-- Swiper -->
<div class="swiper-container">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
  </div>
  <!-- Add Pagination -->
  <div class="swiper-pagination"></div>
</div>