作者:认识你不笑嘻嘻 | 来源:互联网 | 2023-02-04 10:20
你如何得到目前在榆树的焦点?我知道如何使用Elm 设置焦点,但我找不到任何功能来检测当前有焦点的内容.
1> Chad Gilbert..:
在榆树琅/ 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 () ]
这是ellie-app.com上的一个工作示例.