长按事件封装

/**
 * @description 移动端长按事件
 * @ele DOM节点
 * @func 长按后的回调函数
*/
export const longPress = function(ele, func, timeout = 500) {
  let timer
  ele.addEventListener('touchstart', function(e) {
    // 开启定时器前先清除定时器,防止重复触发
    clearTimeout(timeCount)
    // 开启延时定时器
    timer = setTimeout(function() {
      // 调用长按之后的逻辑函数func
      func()
    }, timeout)
  })
  ele.addEventListener('touchmove', function(e) {
    // 若阻止默认事件,则在长按元素上滑动时,页面不滚动
    e.preventDefault()
    // 长按过程中,手指是不能移动的,若移动则清除定时器,中断长按逻辑
    clearTimeout(timer)
  })
  ele.addEventListener('touchend', function(e) {
    // 若手指离开屏幕时,结束长按逻辑
    clearTimeout(timer)
  })
}
/**
* @description 事件监听的兼容封装
* @ele DOM节点
* @type 事件名
* @handle 处理函数
*/ 
function _attachEvent(ele, type, handle) {
    if (ele.addEventListener) {
        ele.addEventListener(type, handle)
    }else if (ele.attachEvent) {
        // 兼容IE7|8
        ele.attachEvent( type, handle)
    }
}
/**
 * @description PC长按事件做IE7|8的兼容
 * @ele DOM节点
 * @func 长按后的回调函数
*/
export const longPress_pc = function(ele, func, timeout = 500) {
  let timer
  _attachEvent(ele, 'touchstart', function(e) {
    // 开启定时器前先清除定时器,防止重复触发
    clearTimeout(timeCount)
    // 开启延时定时器
    timer = setTimeout(function() {
      // 调用长按之后的逻辑函数func
      func()
    }, timeout)
  })
  _attachEvent(ele, 'touchmove', function(e) {
    // 若阻止默认事件,则在长按元素上滑动时,页面不滚动
    e.preventDefault()
    // 长按过程中,手指是不能移动的,若移动则清除定时器,中断长按逻辑
    clearTimeout(timer)
  })
  _attachEvent(ele, 'touchend', function(e) {
    // 若手指离开屏幕时,结束长按逻辑
    clearTimeout(timer)
  })
}

你可能感兴趣的:(各种手写实现,javascript,开发语言,手写实现)