簡體   English   中英

event.preventDefault() 或 event.stopPropagation() 不適用於 keyUp 事件

[英]event.preventDefault() or event.stopPropagation() not working with keyUp event

指令文件:我正在嘗試這樣做,如果我的計數器超過 2,它應該停止事件或 keyUp 以反映但它不起作用。 有人可以幫我嗎?

import { Component, HostListener, HostBinding } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

export enum KeyCodes {
  LEFT = 37,
  RIGHT = 39,
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  counter: number = 0;
  fragment: string;
  classBorder: string = '';

  constructor(private _route: ActivatedRoute) {
    // this.fragment = _route.snapshot.fragment;
  }

  @HostListener('document:keyup', ['$event'])
  KeyUpEvent(event: KeyboardEvent) {
    if (event.keyCode == KeyCodes.LEFT) this.counter--;
    if (event.keyCode == KeyCodes.RIGHT) this.counter++;

    if (this.counter > 2) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
}

您可能希望在 OnInit 中為事件創建一個可觀察對象,然后通過管道將其僅獲取發出的前 2 個值:

export class AppComponent implements OnInit {

  ngOnInit() {
    fromEvent(document, 'keydown').pipe(
      filter((e: KeyboardEvent) => e.keyCode === KeyCodes.LEFT),
      take(2),
    ).subscribe(
      (x: KeyboardEvent) => console.log(x)
    )
  }
}

preventDefault()只禁用瀏覽器的默認行為,它通常用於防止刷新某些事件和類似的事情。

您還可以使用takeUntil()來等待另一個可觀察的觸發,以獲取像您這樣稍微復雜的邏輯。

counter = 0
countSubject = new Subject

get count$() {
  return this.countSubject.asObservable()
}

ngOnInit() {
  fromEvent(document, 'keydown').pipe(
    tap((e: KeyboardEvent) => {
      if (e.keyCode === KeyCodes.LEFT) {
        this.countSubject.next(++this.counter)
      }
      if (e.keyCode === KeyCodes.RIGHT) {
        this.countSubject.next(--this.counter)
      }
    }),
    takeUntil(this.count$.pipe(
      filter((v:number) => v === 2)
    )),
  ).subscribe(
    (x: KeyboardEvent) => console.log(x)
  )
}

我為你做了一個關於Stackblitz的工作示例。

stopPropagation() 方法用於停止將事件從子元素傳播到父元素,在這種情況下,您正在偵聽文檔的 keyup 事件。 (就像從整個文檔中監聽事件一樣)。

也許您應該更改偵聽 keyup 事件的目標。

是一個非常簡單的 stopPropagation() 示例與 keyup 事件一起使用。

您無需阻止任何事情,只需使用正確的邏輯即可。

試試這個:

KeyUpEvent(event: KeyboardEvent) {
    if (event.keyCode == KeyCodes.LEFT) this.counter--;
    if (event.keyCode == KeyCodes.RIGHT) this.counter += this.counter < 2;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM