vue自动滚动组件 可以支持鼠标滚轮操作

vue自动滚动组件 可以支持鼠标滚轮操作

<!--
*@AutoScrollList
*@author GYY
*@date 2022/7/20 11:22
-->
<template>
  <div ref="scrollMain" class="auto-scroll-list-main" @click="autoScrollClick($event)"
       :key="keyValue" @mouseover="mEnter" @mouseleave="mLeave"
  >
      <div ref="scrollItemBox" class="seamless-warp-box" >
        <slot/>
      </div>
      <div v-html="copyHtml" class="seamless-warp-box"></div>
  </div>
</template>

<script>

export default {
  name: 'AutoScrollList',
  props: {
    listData: {
      type: Array
    },
    isPause: {
      type: Boolean,
      default: false
    },
    keyValue: { type: [String,Number], default: '' }
  },
  mounted() {
    // 如果列表数据是异步获取的,记得初始化在获取数据后再调用
    //this.initScroll()
  },
  data() {
    return {
      scrollTop: 0, //列表滚动高度
      speed: 70, //滚动的速度
      copyHtml: null,
      scrollInterval: null,
    }
  },
  watch: {
    isPause(newValue, _) {
      if (newValue) {
        this.mEnter()
      } else {
        this.mLeave()
      }
    },
    listData:{
      deep:true,
      immediate:false,
      handler(newValue, _) {
        this.mEnter()
        this.initScroll()
      }
    },
  },
  methods: {
    initScroll() {
      this.$nextTick(() => {
        this.copyHtml = this.$refs.scrollItemBox.innerHTML
        this.startScroll()
      })
    },
    // 鼠标移入停止滚动
    mEnter() {
      if (this.scrollInterval) {
        clearInterval(this.scrollInterval)
        this.scrollInterval=null
      }
    },
    // 鼠标移出继续滚动
    mLeave() {
      this.startScroll()
    },
    // 开始滚动
    startScroll() {
      //在当前位置开始滚动
      this.scrollTop=this.$refs.scrollMain.scrollTop
      this.scrollInterval = setInterval(this.scroll, this.speed)
    },
    // 滚动处理方法
    scroll() {
      this.scrollTop=this.scrollTop+1
      this.$refs.scrollMain.scrollTop=this.scrollTop
      // 获取需要滚动的盒子的高度
      let scrollItemBox = this.$refs.scrollMain.scrollHeight/2
      // 当判断滚动的高度大于等于盒子高度时,从头开始滚动
      if (this.scrollTop >= scrollItemBox) {
        this.scrollTop = 0
      }
    },
    autoScrollClick(e) {
      let index = e.target.dataset.index
      if (index === undefined) {
        return
      }
      //默认是number 自己改
      this.$emit('autoScrollClick', Number(index))
    }
  },
  destroyed(){
    this.mEnter()
  }
}
</script>

<style lang="scss" scoped>
.auto-scroll-list-main {
  overflow: auto;
  height: 100%;
}

.auto-scroll-list-main::-webkit-scrollbar {
  display: none
}

.seamless-warp-box {
  width: 100%;
}
</style>



  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值