以下是一个简单的vue无缝轮播图实现:

HTML代码:

<template>
  <div class="carousel">
    <div class="carousel-list" :style="{left: left}">
      <div v-for="(item, index) in items" :key="index" class="carousel-item">
        <img :src="item.img" alt="">
      </div>
    </div>
  </div>
</template>

CSS代码:

.carousel {
  position: relative;
  width: 100%;
  height: 500px;
  overflow: hidden;
}

.carousel-list {
  position: absolute;
  top: 0;
  left: 0;
  width: 10000px;
  height: 100%;
  transition: left 0.5s ease-in-out;
}

.carousel-item {
  float: left;
  width: 100%;
  height: 100%;
}

JS代码:

<script>
export default {
  data() {
    return {
      items: [
        { img: 'https://picsum.photos/800/500?random=1' },
        { img: 'https://picsum.photos/800/500?random=2' },
        { img: 'https://picsum.photos/800/500?random=3' },
        { img: 'https://picsum.photos/800/500?random=4' },
        { img: 'https://picsum.photos/800/500?random=5' }
      ],
      currentIndex: 0,
      left: 0
    }
  },
  mounted() {
    this.timer = setInterval(this.next, 3000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    next() {
      this.currentIndex++
      this.left = -this.currentIndex * 100 + '%'
      if (this.currentIndex >= this.items.length) {
        this.currentIndex = 0
        this.left = 0
      }
    }
  }
}
</script>

这个轮播图由一个父容器包含一个子容器,子容器包含多个轮播项。子容器的宽度是所有轮播项宽度之和,通过改变子容器的left值,实现轮播图的滑动效果。定时器控制轮播图自动滑动,滑动到最后一个轮播项时,将currentIndex和left值重置为0,实现无缝循环滑动。

vue实现一个定时无缝滚动的轮播图

原文地址: https://www.cveoy.top/t/topic/btGz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录