angular/ionic自定义click

项目既要用于PC网页,又要在iPad之类的移动设备上使用。
在iPad上的这种大屏设备上用户的手指点击按钮时,可能会发生一个细微的位移导致不能触发click事件。
会给用户一种不太灵敏的感觉,为解决此问题写一个指令代替click。

直接贴上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@Directive({
selector: '[yun-click]'
})

export class YunClickDirective implements OnInit, OnDestroy {
@Output('yun-click') eventClick = new EventEmitter();

unsubscribe: () => void;

constructor(private platform: Platform,
private renderer: Renderer2,
private element: ElementRef) {
}

ngOnInit() {
if (this.platform.is('mobile') || this.platform.is('mobileweb') || this.platform.is('phablet') || this.platform.is('tablet')) {
this.yunTouch();
} else {
this.yunClick();
}
}

// touch事件,移动端且滑动距离小于30px时触发
yunTouch() {
let startX, startY, endX, endY;
// 监听touchstart
this.unsubscribe = this.renderer.listen(
this.element.nativeElement, 'touchstart', (event: TouchEvent) => {
let touch = event.targetTouches[0];
startX = touch.pageX;
startY = touch.pageY;
console.log(startX, startY);
});
// 监听touchmove
this.unsubscribe = this.renderer.listen(
this.element.nativeElement, 'touchmove', (event: TouchEvent) => {
let touch = event.targetTouches[0];
endX = touch.pageX;
endY = touch.pageY;
console.log(endX, endY);
});
// 监听touchend
this.unsubscribe = this.renderer.listen(
this.element.nativeElement, 'touchend', (event: TouchEvent) => {
let distanceX = Math.abs(endX - startX), distanceY = Math.abs(endY - startY);
console.log(distanceX, distanceY);
let distance = Math.sqrt((Math.pow(distanceX, 2) + Math.pow(distanceY, 2))); // 计算滑动距离
console.log(distance);
if (distance < 30 || !endX || !endY) { // 没有滑动时,不触发touchmove,需要判断
this.eventClick.emit(event);
}
});
}

// click事件
yunClick() {
this.unsubscribe = this.renderer.listen(
this.element.nativeElement, 'click', event => {
console.log(event);
this.eventClick.emit(event);
});
}

ngOnDestroy() {
this.unsubscribe();
}

}

使用时和click一样使用,把click换成yun-click。哦 不要忘记添加到module里。