【发布时间】:2017-05-12 03:02:46
【问题描述】:
您如何获得 Elm 中的当前焦点?我知道如何设置 Elm 的焦点,但我找不到任何功能来检测当前有焦点的内容。
【问题讨论】:
标签: elm
您如何获得 Elm 中的当前焦点?我知道如何设置 Elm 的焦点,但我找不到任何功能来检测当前有焦点的内容。
【问题讨论】:
标签: elm
elm-lang/dom 包允许在给定 ID 的元素上设置焦点,但它不允许您获取当前焦点元素。它暗示您可以为此使用document.activeElement。为此,您必须使用端口。
这是一个人为的例子。假设您有一个 Model,其中包含当前选定的 id 以及我们将很快创建的一些文本框的所有 id 的列表。
type alias Model =
{ selected : Maybe String
, ids : List String
}
我们将使用的 Msgs 将能够查询焦点以及使用 Dom 库设置焦点:
type Msg
= NoOp
| FetchFocused
| FocusedFetched (Maybe String)
| Focus (Maybe String)
为此,我们需要两个端口:
port focusedFetched : (Maybe String -> msg) -> Sub msg
port fetchFocused : () -> Cmd msg
调用这些端口的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);
});
视图显示当前选择的 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 ] [] ]
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 () ]
【讨论】:
Browser.Dom 而不仅仅是 Dom。 (b) 使用Browser.Element 而不是Html.program 来表示main 函数(并重新制定初始值)。 (c) 在更新的分支中使用(model, Cmd) 而不是model ! [cmds] 形式(在Focus 分支中使用(model, Cmd.batch [cmds]))。 (d) 使用String.fromInt 和Maybe.withDefault 准备文本输出。见这里:ellie-app.com/b8bF4FXGbWca1