vue2实现反复轮播(走左往右变成从右往左)

DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Documenttitle>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
    style>
    <script src="./unocss.js">script>
    <script src="./vue.js">script>
  head>
  <body>
    <div id="app" class="h-100vh flex items-center justify-center">
      <div>
        <div class="w-220px overflow-hidden">
          <div class="inline-flex gap-10px transition-all" ref="carouselContainer">
            <div :class="item.class" v-for="item in list">{{item.name}}div>
          div>

          <div
            class="inline-flex gap-10px transition-all mt-10px"
            :style="{
            transform: `translateX(${-maxScrollLeft - scrollLeft}px)` 
          }"
          >
            <div :class="item.class" v-for="item in list">{{item.name}}div>
          div>
        div>
      div>
    div>

    <script>
      new Vue({
        el: '#app',
        data() {
          return {
            list: [
              {
                name: '测试11111',
                class: 'border-1px border-solid border-red w-100px h-80px rounded-5px p-10px',
              },
              {
                name: '测试33333',
                class: 'border-1px border-solid border-orange w-120px h-80px rounded-5px p-10px',
              },
              {
                name: '测试2222',
                class: 'border-1px border-solid border-green w-100px h-80px rounded-5px p-10px',
              },
              {
                name: '测试4444',
                class: 'border-1px border-solid border-green w-100px h-80px rounded-5px p-10px',
              },
            ],
            scrollLeft: 0,
            scrollAmount: 5, // 每次滚动的距离
            scrollTimer: null,
            maxScrollLeft: 230,
            change: false,
          }
        },
        mounted() {
          this.startScrolling()
        },
        beforeDestroy() {
          this.stopScrolling()
        },
        methods: {
          startScrolling() {
            this.scrollTimer = setInterval(() => {
              if (this.change) {
                if (this.scrollLeft == 0) {
                  this.change = false
                }
                this.scrollLeft += this.scrollAmount // 向左滚动
              } else {
                if (-this.maxScrollLeft > this.scrollLeft) {
                  this.change = true
                }
                this.scrollLeft -= this.scrollAmount // 向右滚动
              }
              this.$refs.carouselContainer.style.transform = `translateX(${this.scrollLeft}px)`
            }, 100) // 每100毫秒滚动一次
          },
          stopScrolling() {
            clearInterval(this.scrollTimer)
          },
        },
      })
    script>
  body>
html>

你可能感兴趣的:(javascript,前端,vue.js)