如何在 Elm 中同时监听 keypress 和 keydown 事件?

at.*_*at. 5 elm

我想同时收听Elm 中的keypresskeydown事件。但是,如果我有以下内容,则只会keydown监听事件:

textarea
    [ onWithOptions "keypress" (Options False True) <| Json.Decode.map KeyPress keyCode
    , onWithOptions "keydown" (Options False True) <| Json.Decode.map KeyDown keyCode
    ] []
Run Code Online (Sandbox Code Playgroud)

如果我将 the 更改Options为 not preventDefault,那么这两个事件都会被监听。但我需要preventDefault为了不让 Tab 键改变焦点。

有什么办法可以在榆树中做到这一点?

HPa*_*ker 5

在 Elm 19 中,要访问按下的键,您可以使用Browser.Events,它是Elm 浏览器库的一部分。如果要捕获按下的键,可以使用以下方法:

import Json.Decode as Decode

type Key
  = Character Char
  | Control String

subscriptions : Model -> Sub Msg
subscriptions model =
    Browser.Events.onKeyDown keyDecoder

keyDecoder : Decode.Decoder Msg
keyDecoder =
    Decode.map toKey (Decode.field "key" Decode.string)


toKey : String -> Msg
toKey string =
    case String.uncons string of
        Just ( char, "" ) ->
            PressedLetter char

        _ ->
            Control string
Run Code Online (Sandbox Code Playgroud)

这里改编。


小智 1

Elm 0.19 之前,我建议您使用elm-lang/keyboard。该软件包使用订阅,并且非常易于使用。您可以同时订阅 keydown 和 keyup。

对于您的具体情况:按键事件的默认操作是触发按键事件。如果您阻止这种默认行为,您将不会收到按键事件。

您可以在此处阅读有关 keydown 事件的更多信息

也许您只需要使用 keyup 和 keydown 。

我希望它对你有帮助。