移動端H5長按事件 vue自定義指令


 1 import Vue from 'vue'
 2 Vue.directive('longpress', function (el, binding){
 3   var timer = null;
 4   var start = function (e) {
 5       // 如果是點擊事件,不啟動計時器,直接返回
 6       if (e.type === 'click'){
 7           return
 8       }
 9       if (timer == null){
10           // 創建定時器 ( 2s之后執行長按功能函數 )
11           timer = setTimeout(function () {
12               //執行長按功能函數
13               binding.value()
14           },2000)
15       }
16   }
17   var cancel = function () {
18       if (timer !== null){
19           clearTimeout(timer)
20           timer = null
21       }
22   }
23 
24   // 添加事件監聽器
25   el.addEventListener("mousedown", start);
26   el.addEventListener("touchstart", start);
27 
28   // 取消計時器
29   el.addEventListener("click", cancel);
30   el.addEventListener("mouseout", cancel);
31   el.addEventListener("touchend", cancel);
32   el.addEventListener("touchcancel", cancel);
33 })

1.在src目錄下 新建文件夾utils文件夾,然后新建derective.js,復制上方代碼,粘貼到derective.js;
2.在main.js中引入 該自定義指令js
3.在html中可以這樣使用即可 

<h2 v-longpress="handleLongClick">測試長按事件是否生效</h2>

總結:支持移動端跟pc端

 
       


免責聲明!

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



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