如何修改 Rxjs 事件以监听按键按下?

huangapple go评论81阅读模式
英文:

How to modify Rxjs event to listen keys pressed?

问题

我使用 这个 RXjs 解决方案来实现快捷键。

我使用以下条件来捕捉左Shift + m键:

const toogle$ = shortcut([KeyCode.ShiftLeft, KeyCode.KeyM]);

问题在于它仅在我按下并释放这些键时才起作用。如何修改此示例,以便在用户按下键并保持按住它们时也能起作用?

英文:

I use this RXjs solution for hotkeys.

I use this condition to catch leftSfidt + m keys:

const toogle$ = shortcut([KeyCode.ShiftLeft, KeyCode.KeyM]);

Problem is it works only when I press and unpress these keys. How to modify this example in case when user pressed keys and keep them?

答案1

得分: 4

只使用 fromEvent 从事件中获取键按下事件:

const { fromEvent, filter } = rxjs;

fromEvent(document, 'keydown').pipe(
  filter(e => e.shiftKey && e.keyCode === 77)
).subscribe(e => console.log('We got a shift m'));

请注意,在 HTML 部分,需要引入 RxJS 库:

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.8.0/rxjs.umd.min.js"></script>

点击这里将焦点放在片段的 iframe 上,然后它将开始接收键盘事件。

英文:

Just use from event keydown

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const { fromEvent, filter } = rxjs;

fromEvent(document, &#39;keydown&#39;).pipe(
  filter(e =&gt; e.shiftKey &amp;&amp; e.keyCode === 77)
).subscribe(e =&gt; console.log(&#39;We got a shift m&#39;));

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.8.0/rxjs.umd.min.js&quot;&gt;&lt;/script&gt;
Click here to get the snippet&#39;s iframe into focus before it will start getting keyboard events

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月7日 22:24:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定