长按时防止点击事件触发

3
我有以下的angular2模板:
<div (click)="foo()">
   <img (longPress)="bar(1)" (click)="foobar(1)" />
   <img (longPress)="bar(2)" (click)="foobar(2)"/>
</div>

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

<div><img>上的单击事件可以正常处理。当我在图像上进行长按时,会调用bar()函数。然而,在长按后的mouseUp事件中,单击事件会在<img>和父级<div>上触发。

有什么简单的方法可以防止这些单击事件呢?

我现在唯一能想到的就是编写一个自定义属性指令,只在少于500ms的“点击”上触发。但我觉得这有点过头了。

2个回答

5
我创建了一个“长按”和“短按”指令。 长按只在一定时间后触发,而短按则在该阈值以下触发。
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);
    }
}

并且

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);
    }
}

0

你试过将$event作为第一个参数传入,然后在你的bar()方法中调用event.stopPropagation()吗? 类似这样:

<img (longPress)="bar($event,1)" (click)="foobar(1)" />

function bar(event:Event,myNum:number){event.stopPropagation();}


我确实考虑过这样的结构,但那意味着我必须修改被调用的函数。我更希望在属性指令本身中找到解决方案,这样它就不需要特定格式的函数来工作。此外,长按操作将返回一个鼠标按下事件。我不确定阻止鼠标按下事件是否会阻止触发点击事件。 - JasperZelf
@JasperZelf,这只是阻止长按事件传播到父元素,而不是阻止主机元素上触发其他事件吗? - PakiPat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接