🎄🎅 節日特賣:最高 50% 折扣於 UI Initiative, Swiper Studio t0ggles 🎅🎄

v10.1.0 中的滑塊插槽

2023 年 8 月 1 日

問題

所有最新版本的 Safari 瀏覽器都有一個錯誤 (#6650),無法正確 3D 轉換傳遞到插槽中自訂元素。

這會導致 Swiper 特效出現錯誤,這些特效使用 3D 轉換,例如立方體、封面流和(可能)創意特效。

<swiper-container effect="cube">
  <!-- "perspective" prop can't be applied to these slides -->
  <swiper-slide>Slide 1</swiper-slide>
  <swiper-slide>Slide 2</swiper-slide>
  <swiper-slide>Slide 3</swiper-slide>
</swiper-container>

解決方案

在 Swiper v10.1.0 中,我們引入了滑塊插槽來解決此問題。在這種情況下,我們不會將滑塊放入 swiper-container 中,而只放入其內容

<swiper-container effect="cube">
  <!-- Content goes to the first slide (with index 0) -->
  <div slot="slide-0">Slide 1</div>
  <!-- Content goes to the second slide (with index 1) -->
  <div slot="slide-1">Slide 2</div>
  <!-- Content goes to the third slide (with index 2) -->
  <div slot="slide-2">Slide 3</div>
</swiper-container>

Swiper 元件會動態檢查傳遞的滑塊插槽元素數量,並自動建立所需數量的滑塊。對要使用的滑塊插槽數量沒有限制。

但在這種情況下,我們需要重新考慮滑塊的樣式,因為我們在 DOM 中沒有直接的滑塊元素,而且滑塊本身現在位於陰影 DOM 中。

因此建議為滑塊內容使用一些自訂包裝器,例如

<swiper-container effect="cube">
  <!-- Content goes to the first slide (with index 0) -->
  <div slot="slide-0" class="slide-content">
    <img class="slide-image" src="path/to/slide-image.jpg" />
    <div class="slide-title">Slide 1</div>
  </div>
  <!-- Content goes to the second slide (with index 1) -->
  <div slot="slide-1" class="slide-content">
    <img class="slide-image" src="path/to/slide-image.jpg" />
    <div class="slide-title">Slide 2</div>
  </div>
  <!-- Content goes to the third slide (with index 2) -->
  <div slot="slide-2" class="slide-content">
    <img class="slide-image" src="path/to/slide-image.jpg" />
    <div class="slide-title">Slide 3</div>
  </div>
  ...
</swiper-container>
<style>
  /* make sure slide content takes all available slide size */
  .slide-content {
    width: 100%;
    height: 100%;
    position: relative;
  }
  /* slide image */
  .slide-image {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  /* slide title */
  .slide-title {
    color: #fff;
    position: absolute;
    left: 32px;
    bottom: 32px;
    font-weight: bold;
    font-size: 32px;
  }
</style>

現在一切都正常運作(在 Safari 中)

附註

一如既往,如果您喜歡 Swiper,請透過捐款或承諾來支持專案

並查看我們的進階專案

您的支持對我們意義重大!