乐趣区

关于前端:头像循环滚动实现的记录

背景:须要用户头像(3 个)左边局部叠层展现,并且反对循环滚动

实现:
扭转 dom 上绑定的款式 id,论循替换

<template>
  <div class="slider-headimg">
    <div class="out">
      <div class="inner">
        <div class="img" ref="headimgList" v-for="(item,index) in sliderHeadimgList" :key="index">
          <img :src="item.headImgUrl">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    sliderHeadimgList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      timer: null,
      // 定义地位数组
      idArr: ['first', 'second', 'right', 'last']
    }
  },
  mounted () {this.init()
  },
  destroyed () {if (this.timer) {clearInterval(this.timer)
    }
  },
  methods: {init () {
    // 初始化图片地位,依据 id 不同,初始化款式
      var img = this.$refs.headimgList
      img[0].id = this.idArr[0]
      img[1].id = this.idArr[1]
      img[3].id = this.idArr[3]
      for (let i = 0; i < (this.sliderHeadimgList.length - 4); i++) {this.idArr.splice(3, 0, 'left')
      }
      this.initialize()
      // 定时器图片轮播
      this.timer = setInterval(this.next, 1000)
    },
    next () {
    // 将地位数组的最初一个元素删除,并将删除元素增加到地位数组第一个
      this.idArr.unshift(this.idArr.pop())
      this.initialize()},
    // 将地位数组元素作为 id 赋值给 img,达到轮播成果
    initialize () {
      var img = this.$refs.headimgList
      for (var i = 0; i < img.length; i++) {img[i].id = this.idArr[i]
      }
    }
  }
}
</script>

<style lang="less">
.slider-headimg {
  position: relative;
  display: flex;
  align-items: center;
  width: 200px;
  padding-bottom: 55px;
  margin-right: 10px;
}

.out {
  width: 100%;
  height: 100%;
  position: relative;

  .inner {
    width: 100%;

    .img {
      width: 48px;
      height: 48px;
      position: absolute;
      transition: 0.3s;
      display: flex;
      border-radius: 50%;
      border: 1px solid #fff;

      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }
  }

  // 设置 id 款式
  #last {
    display: flex;
    transform: translateX(48px);
    z-index: 3;
    opacity: 1;
  }

  #first {
    display: flex;
    transform: translateX(96px);
    z-index: 2;
    opacity: 1;
  }

  #second {
    display: flex;
    transform: translateX(144px);
    z-index: 1;
    opacity: 1;
  }

  #left {
    display: none;
    transform: translateX(-48px);
    z-index: 1;
    opacity: 0;
  }

  #right {
    display: flex;
    transform: translateX(240px);
    z-index: 1;
    opacity: 0;
  }
}
</style>
退出移动版