느릅 나무에서 현재 포커스를 어떻게 얻습니까? 나는 을 느낀다. 엘름을 가지고 포커스를 맞춘다.하지만 현재 포커스가 무엇인지 감지 할 수있는 기능을 찾을 수 없다.느릅 나무 - 현재 포커스를 어떻게 감지합니까?
3
A
답변
7
elm-lang/dom 패키지는 ID가 지정된 요소에 포커스를 설정할 수 있지만 현재 포커스가있는 요소를 가져올 수는 없습니다. 이 경우 document.activeElement
을 사용할 수 있음을 알립니다. 그렇게하려면 포트를 사용해야합니다.
다음은 인위적인 예제입니다. 현재 선택된 ID와 곧 작성할 일부 텍스트 상자의 모든 ID 목록이 포함 된 Model
이 있다고 가정 해 보겠습니다.
type alias Model =
{ selected : Maybe String
, ids : List String
}
우리가 초점에 대해 문의 할 수 있습니다 사용뿐만 아니라 초점을 설정하는 돔 라이브러리를 사용하게 될 수신함을 :
: 그 내용은type Msg
= NoOp
| FetchFocused
| FocusedFetched (Maybe String)
| Focus (Maybe String)
을, 우리는 두 개의 포트가 필요합니다 현재 document.activeElement
에보고 이러한 포트를 호출
port focusedFetched : (Maybe String -> msg) -> Sub msg
port fetchFocused :() -> Cmd msg
자바 스크립트 :
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() ]