vue自定义指令实现自动滚动可配置

autoScroll.js

let timer = null //定时器
let isScrolling = true //是否滚动

export default {
  bind(el, binding, vnode) {
    init(el, binding, vnode)
  },
  update(el, binding, vnode) {
    // 当绑定值更新时,停止当前滚动并重新初始化
    clearTimeout(timer)
    init(el, binding, vnode)
  },
  unbind(el) {
    // 清理定时器
    clearTimeout(timer)
  }
}

function init(el, binding, vnode) {
  // 鼠标移入时暂停滚动
  el.addEventListener('mouseenter', () => {
    if (options.pauseOnHover) {
      isScrolling = false
      timeout(el, options)
    }
  })

  // 鼠标点击时暂停滚动
  el.addEventListener('click', () => {
    if (options.pauseOnHover) {
      isScrolling = false
      timeout(el, options)
    }
  })

  // 触摸时暂停滚动
  el.addEventListener('touchstart', () => {
    if (options.pauseOnHover) {
      isScrolling = false
      timeout(el, options)
    }
  })

  const options = binding.value

  timer = setTimeout(() => {
    startScroll(el, options)
  }, 1000)
}

// 开始滚动函数
function startScroll(el, options) {
  const scrollHeight = el.scrollHeight // 元素可滚动高度,包括不可见区域部分
  const clientHeight = el.clientHeight // 可见区域高度

  el.scrollTop += options.speed //滚动速度 1
  if (el.scrollTop >= scrollHeight - clientHeight) {
    clearTimeout(timer)
    if (options.loop) {
      // 滚动到页面底部,并且开启了循环滚动
      el.scrollTop = 0
      timer = setTimeout(() => {
        startScroll(el, options)
        isScrolling = true
      }, 1000)
    } else {
    }
  } else {
    timer = setTimeout(() => {
      startScroll(el, options)
    }, 5)
  }
}

function timeout(el, options) {
  if (!isScrolling) {
    clearTimeout(timer)
    let second = 5
    // 定时器 N 秒后执行一次 startScroll 函数
    timer = setTimeout(() => {
      startScroll(el, options)
      isScrolling = true
    }, second * 1000)
  }
}

vue文件中使用

<template>
  <div class="page" v-auto-scroll="scrollOptions">
    <beack></beack>
    <img
      ref="lastItem"
      class="demo"
      src="path"
      alt=""
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      scrollOptions: {
        speed: 1, // 滚动速度(每5毫秒滚动的像素数)
        pauseOnHover: true, // 鼠标移入停止滚动
        loop: true // 循环滚动
      }
    }
  }
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值