在Elm中如何获取当前焦点?我知道如何用Elm设置焦点,但是我找不到任何功能来检测当前焦点。
document.activeElement
来实现。要做到这一点,您需要使用端口 (ports)。Model
。type alias Model =
{ selected : Maybe String
, ids : List String
}
type Msg
= NoOp
| FetchFocused
| FocusedFetched (Maybe String)
| Focus (Maybe String)
为此,我们需要两个端口:
port focusedFetched : (Maybe String -> msg) -> Sub msg
port fetchFocused : () -> Cmd msg
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);
});
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 () ]
这是一个在ellie-app.com上的实际工作示例。
Browser.Dom
而不是仅使用Dom
。(b)对于main
函数,使用Browser.Element
代替Html.program
(并重新定义init值)。 (c)在update的分支中使用(model,Cmd)
而不是model![cmds]
形式(在Focus
分支中使用(model,Cmd.batch [cmds])
)。 (d)使用String.fromInt
和Maybe.withDefault
来准备文本输出。请参见此处:https://ellie-app.com/b8bF4FXGbWca1 - awagner