4

swiper实现异形滚动

 3 years ago
source link: https://segmentfault.com/a/1190000040589452
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Swiper is the free and most modern mobile touch slider with hardware accelerated transitions and amazing native behavior. It is intended to be used in mobile websites, mobile web apps, and mobile native/hybrid apps.

使用场景-过渡效果

实现一个异形轮播图。支持手势左右滑动切换中心图。

image.png

实现异形滚动的原理

中心页(class: swiper-slide-activescale:1,其他页(class: swiper-slide) scale(0<x<1)来实现中心页在用户视觉中心的效果。scale留白区域通过swiper的配置项( 调整每个swiper) + css样式(整体元素微调) 来消除。

代码参考(部分)

index.vue:

    <div class="gallery-wrapper">
      <!-- Slider main container -->
      <div class="swiper-container">
          <!-- Additional required wrapper -->
          <div class="swiper-wrapper">
              <!-- Slides -->
              <div 
                class="swiper-slide" 
                v-for="(item,index) in images"
                :key="`${item.src}-index`"
              > 
                <img 
                  v-lazy="item.src" 
                  :key="item.src"
                  class="image-content"

                <v-touch 
                  tag="div"
                  @tap="onTap(index)"
                >
                <img 
                  src="./../../../assets/art-picture/scale-icon.png"
                  alt="放大"
                  class="scale-icon"
                />
                </v-touch>

                <!-- <div class="swiper-lazy-preloader">loading...</div> -->
            </div>
          </div>
      </div>
    </div>

style.less:

.swiper-container {
      width: 100%;
      height:100%;
    }
      
    .swiper-container > .swiper-wrapper{
      /** active 图片有阴影超出 */
      overflow-y:visible;
      /**
      * 针对swiper 调整offset
      * pre/next容器边框漏出:20
      * 设计稿边距:17.5
      * 17.5 + 20 = 37.5px
      */
      // margin-left:-0.375rem;
    }
  
    .swiper-slide {
      position:relative;
      box-sizing: border-box;
      padding:0.3rem 0.3rem 0.9rem 0.3rem;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: 300ms;
      width:3rem;
      height:4.25rem;
      transform: scale(0.74);
      background-image:url('../../../assets/art-picture/pic-border.png');
      background-repeat:  no-repeat;
      background-position:center ;
      background-size:100% 100%;
      img[lazy="loading"] {
        width: 0.3rem;
        height:0.3rem;
      }
    }
    .swiper-slide:not(.swiper-slide-active){
      /**
       * 计算scale造成的边距误差 
       * 设计稿缩放:0.74 设计稿当前播放的容器宽度/屏幕宽度:300/375
       * scale产生的误差:300*(1-0.74)=78px
       * 标准值17.5
       * 消除误差:78/2- 17.5/2  = 30.25px;
       */
      // margin-left:-0.3025rem; 
      // margin-right:-0.3025rem;
      /**
      * 计算垂直居中时候背景图阴影造成的误差
      * 实际位置:365*0.74/2 = 135.5
      * 当前位置:425*0.74/2 = 157.25
      * 误差:(157.25 - 135.5)/2 = 11.1px
      */
      margin-top:-0.111rem;
    }
  
    .swiper-slide-active{
      transform: scale(1);
      width: 3rem !important;
      height:4.25rem !important;
      /**
      * 消除边距计算对当前播放容器的误差
      * 边距影响:78/2 - 30.25
      * 消除误差:17.5 - (78/2 - 30.25) = 8.75px
      */
      // margin-left:0.0875rem !important;
      // margin-right:0.0875rem !important;
    }
  ...

  // 需要变化的部分配置
  get parameters() {
    const parameters = {
      spaceBetween: -0.225 * this.rootFontSize,
      slidesOffsetBefore: 0.375 * this.rootFontSize,
      slidesOffsetAfter: -0.375 * this.rootFontSize,
      width: 3 * this.rootFontSize,
      height: 4.25 * this.rootFontSize,
      observer: true // handle async
    };
    if (this.images.length === 1) {
      parameters.spaceBetween = 0;
    }
    return parameters;
  }

  public mounted() {
    this.initRootFontSize();
    this.initSwiper({
      initialSlide: this.index
    });
  }

  // get rem(root font-size)
  public initRootFontSize() {
    const html = document.getElementsByTagName('html')[0];
    const rootFontSizeStr = html.style.fontSize;
    this.rootFontSize = parseFloat(rootFontSizeStr);
  }

  public initSwiper(params= {}) {
    const mySwiper = new Swiper('.swiper-container', {
      slidesPerView: 1,
      loop: false,
      preloadImages: false, // preload images:false
      lazy: false, // lazy load images
      on: {
        slideChange: this.onSlideChange,
        sliderMove: () => {
          if (this.slideStatus !== 'fadeInOut') {
            this.slideStatus = 'fadeInOut';
          }
        },
        touchEnd: () => {
          this.slideStatus = 'fadeOut';
        },
      },
      ...this.parameters,
      ...params
    });
    this.mySwiper = mySwiper;
  }

  ...

scale存在的问题:

  • scale 虽然会缩小元素尺寸,但是原来的尺寸空间并不会释放。可以参考 zoom vs transform:scale,这样就会在元素之间产生缩放间距
  • slidesPerView: Number 配置属性设置为数值,很可能会存在中心页始终无法很好出现在中心
  • loop:true 的时候,会复制三分节点。也就是说列表有10项,会有3*10=30个节点,多的时候会对性能产生影响
  • loop:true 最开始和最末尾切换,点击swiper不会触发click事件。在swiper-slide上也不会触发click
  • on:tap(swiper,event) 这个在任何一页点击都会触发。但是:在PC上event测试优秀(包含path属性),到真机上就只有isThrud的了。你就没法知道用户具体点了哪个元素

解决方案一

  • 使用margin-left: x<0;margin-right<0 来消除缩放间距【横竖屏幕切换会存在问题】
  • slidesPerView:'auto' 更好用
  • 禁止loop:true
  • 使用on:tap需慎重,真机测试不可少

完美实现异形(支持横竖屏切换)

虽然经过上面margin 设置负边距,在视觉上实现了异形的效果,但是在横竖屏切换的时候发现了样式被改变的问题。

原因:自己使用CSS 样式的方式修改swiper wrapper和 slider的方式不会被swiperJS 计算在内,导致了translate在计算上出现了问题。

解决1:自己实现活动卡片居中

{
  slidesPerView: 1,
  loop: false,
  preloadImages: false, // preload images:false
  lazy: false, // lazy load images
}

解决2: 不使用CSS样式,怎么实现去除sclae边距问题

image.png

经过使用发现,这个会给slider设置:spaceBetween。可以使用这个替代之前CSS margin的设置,这个距离会被swiepr计算。

centeredSlides默认为left,如何解决首张卡片居中效果?

image.png

所以计算好数值就可以设置了:

{
  spaceBetween: -0.3025 * this.rootFontSize,
  slidesOffsetBefore: 0.375 * this.rootFontSize,
  slidesOffsetAfter: -0.375 * this.rootFontSize,
}

为什么要设置slidesOffsetAfter?
不设置的话在左右拖拽的时候会出现贴边的BUG。

解决3: 屏幕大小适配(不同机型屏幕 | 横竖屏切换)

  • 在解决2里面设置的数值swiper只支持px,所以设置的必须是rem → px
  • 需要在横竖屏切换的时候再获取最新的rem,更新swiper
  public mounted() {
    this.initRootFontSize();
    this.initSwiper();
    window.addEventListener('resize', this.resizeHandler, false);
  }


  public initRootFontSize() {
    const html = document.getElementsByTagName('html')[0];
    const rootFontSizeStr = html.style.fontSize;
    this.rootFontSize = parseFloat(rootFontSizeStr);
  }  

  public resizeHandler() {
    this.initRootFontSize();
    /** update swiper params */
    this.mySwiper.params.spaceBetween = -0.3025 * this.rootFontSize;
    this.mySwiper.params.slidesOffsetBefore = 0.375 * this.rootFontSize;
    this.mySwiper.params.slidesOffsetAfter = -0.375 * this.rootFontSize;
    this.mySwiper.update();// 关键API
  }

这样下来,布局展示是没有问题了,但是对于异形,可能会出现非活动卡片的宽高发生了变化。如果你对slider的宽高有严格的要求,就需要在配置里指定宽高:

{
  height:4.25 * 
this.rootFontSize,
  width:3 * this.rootFontSize,
}

可以抽取变化配置的函数:

  // 需要变化的部分配置
  get parameters() {
    return {
      spaceBetween: -0.225 * this.rootFontSize,
      slidesOffsetBefore: 0.375 * this.rootFontSize,
      slidesOffsetAfter: -0.375 * this.rootFontSize,
      width: 3 * this.rootFontSize,
      height: 4.25 * this.rootFontSize,
      observer: true // handle async
    };
  }

  public initSwiper(params= {}) {
    const mySwiper = new Swiper('.swiper-container', {
      slidesPerView: 1,
      loop: false,
      preloadImages: false, // preload images:false
      lazy: false, // lazy load images
      on: {
        slideChange: this.onSlideChange
      },
      ...this.parameters,
      ...params
    });
    this.mySwiper = mySwiper;
  }

  public resizeHandler() {
    this.initRootFontSize();
    /** update swiper params */
    Object.keys(this.parameters).forEach(key => {
      const value = this.parameters[key];
      this.mySwiper.params[key] = value;
    });
    this.mySwiper.update();
  }

解决4: 异步加载数据,卡片布局问题

通常list 是从接口获取到然后设置的,可能会遇到卡片布局显示异常的问题。这时候可以尝试下在配置里:

{
 observer:true
}

这样就会更新元素布局了。

解决5:上述4步做完,单张展示下向左贴靠的问题

    // 处理只有一张图片的时候贴左的样式问题
    if (images.length === 1) {
      this.mySwiper.params.spaceBetween = 0;
      this.mySwiper.update();
    }

实现完美异性的方案:

  • spaceBetween/slidesOffsetBefore/slidesOffsetAfter
  • observer: true
  • v-lazy
  • v-touch

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK