Vue实现一个自下而上带有停顿的跑马灯效果

372 阅读1分钟

主要代码如下:

<template>
  <div id="marquee-box" v-show="list.length > 0">
    <i class="horn"></i>
    <div class="content">
      <div class="marquee-box">
        <ul class="item" :class="{ 'marquee-top': animate }">
          <li v-for="(item, index) in list" :key="index">恭喜 {{ item.nick }} 获得 {{ item.name }} 一台</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      animate: false,
      list: [
        { name: '电磁炉', nick: '又一年又三年' },
        { name: '电冰箱', nick: '顽皮捣蛋小精灵' },
        { name: '微波炉', nick: '白云下的棉絮' },
        { name: '烤箱', nick: '芭比美人鱼' },
        { name: '冰箱', nick: '浅夏星空' },
        { name: '消毒柜', nick: '你有没有见过他' },
        { name: '洗碗机', nick: '梦的河流' },
        { name: '烤箱', nick: '山水闲人' },
        { name: '电冰箱', nick: '夜市那么黑' },
        { name: '空调', nick: '恋初雪' },
        { name: '洗衣机', nick: '雨点多日落' },
        { name: '烘干机', nick: '明星紫月' },
        { name: '消毒柜', nick: '浅草带苏烟' }
      ],
      timer: null
    };
  },
  mounted() {
    this.run()
  },
  methods: {
    run() {
      let that = this;
      if (that.list.length >= 1 && that.timer == null) {
        that.timer = setInterval(() => {
          this.animate = true;
          setTimeout(() => {
            that.list.push(this.list[0]);
            that.list.shift();
            that.animate = false;
          }, 500);
        }, 3000);
        this.$once("hook:beforeDestroy", () => {
          clearInterval(that.timer);
        });
      }
    }
  }
};
</script>

<style lang="scss">
#marquee-box {
  width: 7.1rem;
  height: 0.6rem;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  border: 1px solid #FFF;
  border-radius: .2rem;
  
  .horn {
    width: 0.64rem;
    height: 0.64rem;
    background: url('../img/horn.png');
    background-size: 100% 100%;
  }
  .content {
    height: 100%;
    flex: 1;
    border-radius: 0.2rem;
    padding: 0 0.2rem 0 0.1rem;
    box-sizing: border-box;
    
    .marquee-box {
      display: block;
      position: relative;
      width: 100%;
      height: 100%;
      overflow: hidden;
      
      .item {
        width: 100%;
        height: 100%;
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        
        li {
          height: 100%;
          line-height: 0.71rem;
          font-size: 0.24rem;
          color: #FFF;
          max-width: 5.2rem;
          display: block;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
  }
}

.marquee-top {
  transition: all 0.5s;
  margin-top: -0.6rem;

}
</style>

效果图如下:

跑马灯.gif