swiper实现异形滚动

比特织云人
• 阅读 8369

基本信息

官方介绍

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.

文档

使用场景-过渡效果

  • 轮播图

实践

目标

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

swiper实现异形滚动

实现异形滚动的原理

实现异形效果

  • 中心页(class: swiper-slide-activescale:1
  • 其他页(class: swiper-slide) scale(0<x<1)来实现中心页在用户视觉中心的效果。

实现两侧留边效果:

  • css设置每一个swiper-slide的padding值(留白)
  • 设置swiper的spaceBetween 设置为负值,来把3个swiper-slide拉到一屏上来
  • 设置swiper的slidesOffsetBefore和slidesOffsetAfter来消除第一张和最后一张不居中的问题

代码参考(部分)

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;
    }

js:

  ...

  // 需要变化的部分配置
  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边距问题

swiper实现异形滚动

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

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

swiper实现异形滚动

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

{
  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
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
3年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这