gpt4 book ai didi

angular - 如何在 Angular 2 中监听点击并按住?

转载 作者:搜寻专家 更新时间:2023-10-30 21:15:15 24 4
gpt4 key购买 nike

In this link ,您可以在 AngularJS 中找到示例。

但这在 Angular 2 中是如何工作的呢?

最佳答案

一个简单的实现看起来像这样。

@Component({
selector: 'my-app',
template: `
<div>
<h2 (mousedown)="mousedown()" (mouseup)="mouseup()" (mouseleave)="mouseup()">Hello {{name}}</h2>
</div>
`,
})
export class App {
name: string;
timeoutHandler: number;

constructor() {
this.name = 'Angular!'
}
public mouseup() {
if (this.timeoutHandler) {
clearTimeout(this.timeoutHandler);
this.name = "canceled";
this.timeoutHandler = null;
}
}

public mousedown() {
this.timeoutHandler = setTimeout(() => {
this.name = "has been long pressed"
this.timeoutHandler = null;
}, 500);
}
}

它设置了一个超时,如果用户在设定的时间之前点击离开,该超时将被取消。

您可以找到一个可用的 plnkr here .

如果您想要在点击保持时发生某些事情,这也很容易做到,只需将 setTimeout 换成 setInterval。

@Component({
selector: 'my-app',
template: `
<div>
<h2 (mousedown)="mousedown()" (mouseup)="mouseup()" (mouseleave)="mouseup()">Hello {{name}}</h2>
</div>
`,
})
export class App {
name: number = 0;
timeoutHandler;

constructor() {
this.name = -1
}
public mouseup() {
if (this.timeoutHandler) {
clearInterval(this.timeoutHandler);
this.name = 0;
this.timeoutHandler = null;
}
}

public mousedown() {
this.timeoutHandler = setInterval(() => {
this.name += 1;
}, 100);
}
}

可以找到工作的 plnkr here .

关于angular - 如何在 Angular 2 中监听点击并按住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43071160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com