vue实现循环滚动列表

6,666 阅读1分钟

HTML代码

<template>
  <div id="box">
    <div id="con1" ref="con1" :class="{anim:animate==true}" @mouseenter="mEnter" @mouseleave="mLeave">
      <p v-for='(item, index) in items' :key="index">中奖人的名字是--{{item.name}}</p>
    </div>
  </div>
</template>

Vue

export default {
  name: 'LoopScroll',
  data () {
    return {
      animate: false,
      items: [
        {name: '马云'},
        {name: '雷军'},
        {name: '王勤1'},
        {name: '王勤2'},
        {name: '王勤3'},
        {name: '王勤4'},
        {name: '王勤5'},
      ]
    }
  },
  created () {
  },
  mounted () {
    this.timer1 = setInterval(this.scroll, 2000)
  },
  methods: {
    scroll () {
      let con1 = this.$refs.con1
      con1.style.marginTop = '-30px'
      this.animate = !this.animate
      setTimeout(() => {
        this.items.push(this.items[0])
        this.items.shift()
        con1.style.marginTop = '0px'
        this.animate = !this.animate // 这个地方如果不把animate 取反会出现消息回滚的现象,此时把ul 元素的过渡属性取消掉就可以完美实现无缝滚动的效果了
      }, 1000)
    },
    mEnter () {
      clearInterval(this.timer1)
    },
    mLeave () {
      this.timer1 = setInterval(this.scroll, 1000)
    }
  }
}

CSS样式

  #box{
    width: 300px;
    height: 30px;
    line-height: 30px;
    overflow: hidden;
    padding-left: 30px;
    border: 1px solid black;
  }
  .anim{
    transition: all .8s;
  }
  #con1 li{
    list-style: none;
    line-height: 30px;
    height: 30px;
  }