如何制作长按按键时触发的键盘事件流?(飞镖)



如何创建一个KeyBoardEvent的流,该流在长按某个html元素中的键时触发。

同样,我也对Angular2指令(longpress)感兴趣(有同样的想法)。

@Directive(
    selector: '[longpress]')
class LongPress {
  @Output() EventEmitter<KeyboardEvent> longpress =
      new EventEmitter<KeyboardEvent>();
  KeyboardEvent _startEvent;
  @Input() Duration longpressDelay = new Duration(seconds: 2);
  Timer timer;
  @HostListener("keydown", const [r"$event"])
  @HostListener("keyup", const [r"$event"])
  void keyEventHandler(KeyboardEvent event) {
    if (_startEvent == null ||
        _startEvent.type != event.type ||
        _startEvent.keyCode != event.keyCode) {
      if (timer != null) {
        timer.cancel();
      }
      _startEvent = event;
      if(event.type == 'keyup') {
        timer = new Timer(longpressDelay, () {
          longpress.add(_startEvent);
          timer = null;
        });
      }
    }
  }
}

并像一样使用它

<label for="input">Longpress: </label><input id="longpress" longpress (longpress)="longPressed($event)">

我还没有弄清楚如何使指令选择器与(...)一起工作,所以它也能工作:

<label for="input">Longpress: </label><input id="longpress" (longpress)="longPressed($event)">

事件处理(preventDefault)似乎还不能正常工作。将此指令添加到<input>会中断输入中的写入。

一个解决方法是以这种方式订阅keydown/keyup,而不是

LongPress(ElementRef elementRef) {
  (elementRef.nativeElement as Element).onKeyDown.listen(keyEventHandler);
  (elementRef.nativeElement as Element).onKeyUp.listen(keyEventHandler);
}

如果有人感兴趣,下面是typescript版本:

import { Directive, EventEmitter, Output, Input, HostListener } from '@angular/core';
    @Directive({
        selector: '[longpress]'
    })
    export class LongPressDirective {
      @Output() longpress: EventEmitter<KeyboardEvent> = new EventEmitter(true);
      _startEvent: KeyboardEvent;
      @Input() longpressDelay: number = 1000;
      timer: any;
      @HostListener('keydown', ['$event'])
      @HostListener('keyup', ['$event'])
      keyEventHandler(event: KeyboardEvent) {
        if (this._startEvent == null ||
          this._startEvent.type != event.type ||
          this._startEvent.keyCode != event.keyCode) {
          //console.log(event.type, event);
          if (this.timer != null) {
            clearTimeout(this.timer);
          }
          this._startEvent = event;
          if(event.type == 'keydown') {
            this.timer = setTimeout(() => {
              console.log('longpress');
              this.longpress.emit(this._startEvent);
              clearTimeout(this.timer);
              this.timer = null;
            }, this.longpressDelay);
          }
        }
      }
    }

相关内容

  • 没有找到相关文章

最新更新