我如何将键盘组合构建到我的 Elm 应用程序中,例如。“shift + alt + enter”?你会做这样的事情来对按下的单个键做出反应(例如输入键):
import Keyboard
type Msg
= KeyDown Keyboard.KeyCode
type alias Model =
...
update msg model =
case msg of
KeyDown key ->
handleKeyDown key model
subscriptions model =
Sub.batch
[
Keyboard.downs KeyDown
]
handleKeyDown key model =
case key of
13 -> -- Enter key
Debug.log "Other key"
model
_ -> -- Any other key
Debug.log "Other key"
model
view model =
...
Run Code Online (Sandbox Code Playgroud)
但是你怎么能对按下的多个键做同样的事情呢?
您可以使用Keyboard.downs提到的 pdoherty926 以及 aSet来跟踪按下了哪些键。您还需要查看Keyboard.ups以了解何时释放密钥。
这是一个工作示例:
import Html exposing (..)
import Html.App exposing (program)
import Keyboard exposing (..)
import Set exposing (Set)
import Char
main =
program { init = (initialModel, Cmd.none), view = view, update = update, subscriptions = subscriptions }
initialModel =
{ keysDown = Set.empty
}
view : Model -> Html Msg
view model =
text <| toString <| Set.map Char.fromCode model.keysDown
type Msg
= KeyDown KeyCode
| KeyUp KeyCode
type alias Model =
{ keysDown : Set KeyCode
}
update msg model =
case msg of
KeyDown key ->
({ model | keysDown = Set.insert key model.keysDown }, Cmd.none)
KeyUp key ->
({ model | keysDown = Set.remove key model.keysDown }, Cmd.none)
subscriptions _ =
Sub.batch
[ Keyboard.downs KeyDown
, Keyboard.ups KeyUp
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
696 次 |
| 最近记录: |