1. 程式人生 > 其它 >swiper首尾兩項不居中其餘項居中

swiper首尾兩項不居中其餘項居中

技術標籤:javascriptswipereactcss

swiper的使用中有一種場景是首尾兩項靠左或者靠右顯示,其餘項居中顯示,如圖:
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
如果所有項都居中並且露出相鄰項的一部分,可直接如下設定:

const settings = {
  // 兩遍顯示相鄰兩張
  slidesPerView: 'auto',

  // 相鄰兩張間距
  spaceBetween: 12,

  // swiper動態載入
  observer:true, 
  observeParents:true,

  // 當前頁居中顯示
  centeredSlides: true,
}

首尾兩張貼邊,可以加一個引數:

const settings = {
  // 兩遍顯示相鄰兩張
  slidesPerView: 'auto',

  spaceBetween: 12,

  // swiper動態載入
  observer:true, 
  observeParents:true,

  // 當前頁居中顯示
  centeredSlides: true,

  // 第一張和最後一張貼合邊緣 
  centeredSlidesBounds: true, 
}

然後在元件中new Swiper:

  useEffect(() => {
      let mySwiper = new Swiper('.swiper-container'
, settings); mySwiper.on('slideChange',hanldeSlide) return ()=>{ mySwiper.destroy(); } }, []);

需要設定.swiper-wrapper寬為100%,和滑動塊的寬度.swiper-slide
設定完後效果是這樣的:
在這裡插入圖片描述
需要給首尾兩張分別新增左邊距和右邊距:

      .first-last-slide:first-of-type{
        margin-left: 38px;
      }
      .first-last-slide:
last-of-type{ margin-right: 38px; } .swiper-slide{ width: 610px; }

有一個需要注意的地方是,如果先new Swiper之後元件才獲取到swiper裡的資料,比如依賴介面或者props等,必須將下面兩個引數設為true,否則會出現檢視元素時所有滑動項都存在,但是頁面上實際可滑動的只有第一張的情況:

  observer:true, 
  observeParents:true,