榆树 - 我如何检测当前焦点

G41*_*143 5 elm

你如何得到目前在榆树的焦点?我知道如何使用Elm 设置焦点,但我找不到任何功能来检测当前有焦点的内容.

Cha*_*ert 9

榆树琅/ DOM包允许设置获得一个ID的元素上的焦点,但它不会让你获取当前聚焦的元素.它暗示你可以使用document.activeElement它.要做到这一点,你将不得不使用端口.

这是一个人为的例子.假设您有一个Model包含当前所选ID的列表以及我们即将创建的一些文本框的所有ID列表.

type alias Model =
    { selected : Maybe String
    , ids : List String
    }
Run Code Online (Sandbox Code Playgroud)

我们将使用的Msgs将能够查询焦点以及使用Dom库来设置焦点:

type Msg
    = NoOp
    | FetchFocused
    | FocusedFetched (Maybe String)
    | Focus (Maybe String)
Run Code Online (Sandbox Code Playgroud)

为此,我们需要两个端口:

port focusedFetched : (Maybe String -> msg) -> Sub msg

port fetchFocused : () -> Cmd msg
Run Code Online (Sandbox Code Playgroud)

调用这些端口的javascript将报告当前document.activeElement:

var app = Elm.Main.fullscreen()
app.ports.fetchFocused.subscribe(function() {
  var id = document.activeElement ? document.activeElement.id : null;
  app.ports.focusedFetched.send(id);
});
Run Code Online (Sandbox Code Playgroud)

视图显示当前选定的ID,提供了一个按钮列表,这些按钮将焦点设置在下面的一个编号文本框中.

view : Model -> Html Msg
view model =
    div []
        [ div [] [ text ("Currently selected: " ++ toString model.selected) ]
        , div [] (List.map viewButton model.ids)
        , div [] (List.map viewInput model.ids)
        ]


viewButton : String -> Html Msg
viewButton id =
    button [ onClick (Focus (Just id)) ] [ text id ]


viewInput : String -> Html Msg
viewInput idstr =
    div [] [ input [ id idstr, placeholder idstr, onFocus FetchFocused ] [] ]
Run Code Online (Sandbox Code Playgroud)

update功能将它们联系在一起:

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NoOp ->
            model ! []

        FetchFocused ->
            model ! [ fetchFocused () ]

        FocusedFetched selected ->
            { model | selected = selected } ! []

        Focus (Just selected) ->
            model ! [ Task.attempt (always NoOp) (Dom.focus selected), fetchFocused () ]

        Focus Nothing ->
            { model | selected = Nothing } ! [ fetchFocused () ]
Run Code Online (Sandbox Code Playgroud)

这是ellie-app.com上的一个工作示例.