将单击和双击视为同一操作

3
我希望能够执行foo()一次,无论我单击按钮一次或两次。
<span> (click)="foo()" </span>

foo() {
    console.log("You've clicked on foo");
}

我曾尝试使用这个stackoverflow答案,但是点击两次仍然会导致多个console.logs。如何只运行一次此函数?

注意:不是想要三次或四次点击(只需要单击/双击)。

1个回答

1
尝试使用setTimeoutclearTimeout和处理用户点击事件:
<span 
    (click)="func1()" 
    (dblclick)="func2()">
    Hello
</span>

TypeScript:
timer = 0;
delay = 200;
prevent = false;

func1(){
    this.timer = setTimeout(() => {
        if (!this.prevent) {
            this.sayHello();
        } 
        this.prevent = false;
    }, this.delay);
}

func2(){
    clearTimeout(this.timer);
    this.prevent = true;
    this.sayHello();
}

sayHello(){
    console.log('Hello, world!:)');
}

这个StackBlitz示例


@Jedo 非常感谢!很高兴我的帮助对你有所帮助! :) - StepUp

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