1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
6 <title>自定义tap指令</title>
7 <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
8 </head>
9 <body>
10 <div id="app">
11 <button v-tap="todo">按钮</button>
12 </div>
13
14 <script>
15 /*封装tap*/
16 function tap(dom,callback){
17 /*
18 * 要求 没有触发 touchmove 事件
19 * 并且响应速度要比click快
20 */
21 if(dom && typeof dom == 'object'){
22 var isMove = false;
23 var startTime = 0;
24 dom.addEventListener('touchstart',function(e){
25 //console.log('touchstart');
26 //console.time('tap');/*记录tap这个参数现在的时间*/
27 startTime = Date.now();
28 });
29 dom.addEventListener('touchmove',function(e){
30 //console.log('touchmove');
31 isMove = true;
32 });
33 dom.addEventListener('touchend',function(e){
34 //console.log('touchend');
35 //console.timeEnd('tap')/*打印tap这个参数距离上一次记录的时候的时间*/
36 /*判读 是否满足tap 的要求 一般要求tap的响应时间150*/
37 if(!isMove && (Date.now()-startTime) < 150){
38 /*调用 callback*/
39 // callback && callback(e);
40 callback.call(dom, e);
41 }
42 /*重置 参数*/
43 isMove = false;
44 startTime = 0;
45 });
46 }
47 }
48 Vue.directive('tap', {
49 bind: function (el, binding) {
50 tap(el, binding.value)
51 }
52 })
53 new Vue({
54 el: '#app',
55 methods: {
56 todo: function () {
57 console.log('todo');
58 }
59 }
60 })
61 </script>
62 </body>
63 </html>