vue長按事件


來源https://github.com/OFED/translation/issues/3

Vue.directive('longpress', {
  bind: function(el, binding, vNode) {
    // 確保提供的表達式是函數
    if (typeof binding.value !== 'function') {
      // 獲取組件名稱
      const compName = vNode.context.name
      // 將警告傳遞給控制台
      let warn = `[longpress:] provided expression '${binding.expression}' is not a function, but has to be `
      if (compName) { warn += `Found in component '${compName}' ` }

      console.warn(warn)
    }

    // 定義變量
    let pressTimer = null

    // 定義函數處理程序
    // 創建計時器( 1秒后執行函數 )
    let start = (e) => {
      if (e.type === 'click' && e.button !== 0) {
        return
      }

      if (pressTimer === null) {
        pressTimer = setTimeout(() => {
          // 執行函數
          handler()
        }, 1000)
      }
    }

    // 取消計時器
    let cancel = (e) => {
      // 檢查計時器是否有值
      if (pressTimer !== null) {
        clearTimeout(pressTimer)
        pressTimer = null
      }
    }

    // 運行函數
    const handler = (e) => {
      // 執行傳遞給指令的方法
      binding.value(e)
    }

    // 添加事件監聽器
    el.addEventListener('mousedown', start)
    el.addEventListener('touchstart', start)

    // 取消計時器
    el.addEventListener('click', cancel)
    el.addEventListener('mouseout', cancel)
    el.addEventListener('touchend', cancel)
    el.addEventListener('touchcancel', cancel)
  }
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM