Elm 检查 ctrl 键是否按下 onClick

Elm check whether ctrl key pressed onClick

使用elm-html,如何检查点击时是否按下了ctrl键?

"control key down" 我是否需要在其他地方维护某些状态,也许使用键盘模块?如果是这样,那将如何适应 elm-html?

我从一个著名的 elm 示例中改编了以下代码:

import Keyboard
import Html exposing (..)
import Html.Attributes exposing (style)
import Html.Events exposing (onClick)
import Signal exposing(Signal, Mailbox)


type alias Model =
  { count: Int
  , ctrl : Bool
}

initialModel : Model
initialModel = { count = 0, ctrl = False}

type Action = Increment | Decrement | NoOp

update : Action -> Model -> Model
update action model =
  case action of
    Increment ->
      { model | count = model.count + 1 }
    Decrement ->
      { model | count = model.count - 1 }
    NoOp ->
      model


view : Signal.Address Action -> Model -> Html
view address model =
  div []
    [ button [ onClick address Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick address Increment ] [ text "+" ]
    ]


actions : Mailbox Action
actions =
  Signal.mailbox NoOp

model : Signal Model
model =
  Signal.foldp update initialModel actions.signal -- Keyboard.ctrl ?

main =
  Signal.map (view actions.address) model

如何更新模型的 "ctrl" 字段的值?

你首先需要一个能够设置是否按下CTRL的值的Action:

type Action = Increment | Decrement | SetCtrl Bool | NoOp

更新函数中的 case 语句需要处理该新操作:

SetCtrl bool -> { model | ctrl = bool }

现在您需要一个端口,可以将 Keyboard.ctrl 布尔值映射到一个任务,该任务使用新的 Action:

发送信号
port ctrlToAction : Signal (Task.Task Effects.Never ())
port ctrlToAction =
  Signal.map (Signal.send actions.address << SetCtrl) Keyboard.ctrl