你如何获得目前在榆树的关注?我知道如何使用Elm 设置焦点,但我无法找到任何功能来检测当前有焦点的内容。
答案 0 :(得分:8)
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 () ]