防止长按时的点击事件

Jas*_*elf 3 mouseevent stoppropagation long-press angular

我有以下 angular2 模板:

<div (click)="foo()">
   <img (longPress)="bar(1)" (click)="foobar(1)" />
   <img (longPress)="bar(2)" (click)="foobar(2)"/>
</div>
Run Code Online (Sandbox Code Playgroud)

Longpress 是一个自定义属性指令,当鼠标按下 500 毫秒时触发。

<div>和上的点击事件<img>处理得很好。当我长按图像时,会调用 bar() 函数。但是,在 mouseUp 上(长按后),将在<img>和 父级上触发单击事件<div>

如何以最简单的方式阻止这些点击事件。

我现在唯一能想到的就是编写一个自定义属性指令,仅在不到 500 毫秒的“点击”时触发。这对我来说似乎有点过分了。

Jas*_*elf 5

我最终创建了一个“longPress”和一个“shortPress”指令。长按仅在设定的时间后触发,短按仅在低于相同阈值时触发。

import { Directive, HostListener, Output, EventEmitter } from '@angular/core';

@Directive({ selector: '[shortPress]' })

export class ShortPressDirective {

    @Output()
    shortPress = new EventEmitter();

    private _timeout: any;
    private _isShort: boolean;

    @HostListener('mousedown') onMouseDown( e ) {
        this._isShort = true;
        this._timeout = setTimeout(() => {
            this._isShort = false;
        }, 500);
    }

    @HostListener('mouseup') onMouseUp( e ) {
        if (this._isShort) {
            this.shortPress.emit( e );
        }
        clearTimeout(this._timeout);
    }

    @HostListener('mouseleave') onMouseLeave() {
        clearTimeout(this._timeout);
    }
}
Run Code Online (Sandbox Code Playgroud)

import { Directive, HostListener, Output, EventEmitter } from '@angular/core';

@Directive({ selector: '[longPress]' })

export class LongPressDirective {

    @Output()
    longPress = new EventEmitter();

    private _timeout: any;

    @HostListener('mousedown') onMouseDown( e ) {
        this._timeout = setTimeout(() => {
            this.longPress.emit( e );
        }, 500);
    }

    @HostListener('mouseup') onMouseUp() {
        clearTimeout(this._timeout);
    }

    @HostListener('mouseleave') onMouseLeave() {
        clearTimeout(this._timeout);
    }
}
Run Code Online (Sandbox Code Playgroud)