原生javaScript 模拟鼠标长按事件

原生javaScript 模拟鼠标长按事件

实现

/**
 * 长按事件模拟
 * 有些浏览器有长按复制的功能,需清除默认行为
 */

export class LongPress {
  public element: HTMLElement
  private callback: Function = () => {}
  private duration: number
  private timer: any

  constructor(element: HTMLElement, callback: Function, duration = 1000) {
    this.element = element
    this.duration = duration
    this.callback = callback
    this.timer = 0

    this.element.addEventListener('mousedown', this.handleMouseDown.bind(this))
    this.element.addEventListener('mouseup', this.handleMouseUp.bind(this))
    this.element.addEventListener('mouseleave', this.handleMouseLeave.bind(this))
  }

  handleMouseDown(event: MouseEvent) {
    event.preventDefault()
    this.timer = setTimeout(() => {
      this.callback?.(event)
    }, this.duration)
  }

  handleMouseUp(event: MouseEvent) {
    event.preventDefault()
    clearTimeout(this.timer)
  }

  handleMouseLeave(event: MouseEvent) {
    event.preventDefault()
    clearTimeout(this.timer)
  }
}
使用
import {LongPress} from 'xxx'
// 获取要监听事件的dom
const container = document.getElementById('container')

new LongPress(container,()=>{
    console.log('这里进行事件回调')
})

你可能感兴趣的:(utils,javascript,前端)