[Element UI] Carousel 走马灯 各幻灯片设置不同的切换间隔

 

背景: 需要设置走马灯切换的时间间隔,但每张幻灯片的时间间隔不同。

 

自动切换幻灯片方式(失败):尝试动态设置el-carousel的interval属性,但发现最终走马灯只会以设置的最长的时间间隔执行,比如根据幻灯片Change事件,通过幻灯片索引,设置interval的值,有的15秒,有的30秒,但最终走马灯设置到30秒后,之后一直以30秒执行,当interval改为15秒后,依然是30秒运行。

 

手动切换幻灯片方式(成功):

需要定义的变量

data(){
  return {
      carouselIndex: 0,
      carouselRecordTime: 0    
  }      
}    

根据幻灯片索引来进行时间间隔调整,因此使用change事件,用来获取幻灯片索引。同时取消走马灯自动切换, 即 :autoplay="false" 。设置ref,用于调用幻灯片切换API。

<el-carousel ref="carousel" :autoplay="false" @change="carouselChange">
</el-carousel>
 methods:{
   carouselChange(index) {
      this.carouselIndex = index
    }
}

需要根据当前幻灯片索引,当前时间,切换的时间间隔,来判断何时切换。

比如,我需要索引为0-2的幻灯片按15秒来切换幻灯片,其余的幻灯片按30秒来切换幻灯片。

在mouted事件中,通过一个变量(carouseRecordTime)来记录时间 ,然后再根据当前时间(currTime)与记录时间(carouseRecordTime)进行比较,当满足条件后就执行切换,同时更新记录时间(carouseRecordTime)。

mounted() {
    this.carouselRecordTime = new Date().getTime()
   const refreshFrame = () => {
      requestAnimationFrame(() => {
        var dt = new Date();
        let currTime = dt.getTime()
        if (this.carouselIndex > 2 && currTime - this.carouselRecordTime > 30000) {
          this.$refs.carousel.next();
          this.carouselRecordTime = currTime
        }
        else if (this.carouselIndex <= 2 && currTime - this.carouselRecordTime > 15000) {
          this.$refs.carousel.next();
          this.carouselRecordTime = currTime
        }
        refreshFrame();
      })
    }
    refreshFrame();
}

 

posted @ 2024-07-12 16:54  WikiChen  阅读(44)  评论(0编辑  收藏  举报