如何在 Angular 2 中监听点击并按住的声音?

2023-12-31

在这个链接中 https://stackoverflow.com/questions/25180332/how-can-i-listen-for-a-click-and-hold-in-angularjs,你可以在 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);
  }
}

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

你可以找到一个工作plnkrhere http://plnkr.co/edit/msg1VAaBhQoM4l7pqtD4?p=preview.

如果您想要在单击保持时发生某些事情,也很容易做到,只需将 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);
  }
}

可以找到一个可用的 plnkrhere http://plnkr.co/edit/0gCIECkCeqCAjwygF4AF?p=preview.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Angular 2 中监听点击并按住的声音? 的相关文章

随机推荐