html 如何在Elm中的元素上设置焦点?

4c8rllxm  于 2022-12-16  发布在  其他
关注(0)|答案(6)|浏览(140)

如何在Elm中设置Html元素的焦点?我尝试在元素上设置autofocus属性,但它只在页面加载上设置焦点。

vngu2lb8

vngu2lb81#

elm-lang/dom包中的focus函数用于使用Task设置焦点(不使用任何port或JavaScript)。
在内部,它使用requestAnimationFrame来确保在尝试查找要关注的DOM节点之前呈现任何新的DOM更新。
使用示例:

type Msg
    = FocusOn String
    | FocusResult (Result Dom.Error ())

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        FocusOn id ->
            ( model, Dom.focus id |> Task.attempt FocusResult )

        FocusResult result ->
            -- handle success or failure here
            case result of
                Err (Dom.NotFound id) ->
                    -- unable to find dom 'id'
                Ok () ->
                    -- successfully focus the dom

Full example on Ellie

j5fpnvbx

j5fpnvbx2#

解决方法是使用Mutation Observers。将此JavaScript插入到HTML主页或Elm代码的主视图中:

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    handleAutofocus(mutation.addedNodes);
  });
});
var target = document.querySelector('body > div');
var config = { childList: true, subtree: true };
observer.observe(target, config);

function handleAutofocus(nodeList) {
  for (var i = 0; i < nodeList.length; i++) {
    var node = nodeList[i];
    if (node instanceof Element && node.hasAttribute('data-autofocus')) {
      node.focus();
      break;
    } else {
      handleAutofocus(node.childNodes);
    }
  }
}

然后通过包含Html.Attributes.attribute "data-autofocus" ""创建HTML元素。

kqhtkvqz

kqhtkvqz3#

使用elm/html 0.19可以将Html.Attrbutes autofocus设置为True

input [ onInput Code, autofocus True ] []
bvpmtnay

bvpmtnay4#

我最近花了不少时间来探索这个问题,不幸的是,我认为现有的elm-html库不可能做到,但是我想出了一个办法,利用css动画来触发一个事件,并将其嵌入到纯js中。
这是我用一个script节点和一个style节点在Elm中的破解。在我看来,它非常丑陋。

import Html exposing (div, button, text, input, node)
import Html.Events exposing (onClick)
import Html.Attributes exposing (type', class)
import StartApp.Simple

main =
  StartApp.Simple.start { model = model, view = view, update = update }

model = []

view address model =
  -- View now starts with a <style> and <script> (hacky)
  (node "style" [] [ Html.text style ]) ::
  (node "script" [] [Html.text script ]) ::
  (button [ onClick address AddInput ] [ text "Add Input" ]) ::
  model |>
  div []    

type Action = AddInput 

update action model =
  case action of
    AddInput -> (Html.p [] [input [type' "text", class "focus"] []]) :: model

-- Use pure string css (hacky)

style = """
.focus {
  animation-name: set-focus;
  animation-duration: 0.001s;
  -webkit-animation-name: set-focus;
  -webkit-animation-duration: 0.001s;
}
@-webkit-keyframes set-focus {
    0%   {color: #fff}
}
@keyframes set-focus {
    0%   {color: #fff}
}
"""

-- Cheating by embedding pure javascript... (hacky)

script = """
var insertListener = function(event){
 if (event.animationName == "set-focus") {
   event.target.focus();
 }               
}
document.addEventListener("animationstart", insertListener, false); // standard + firefox
document.addEventListener("MSAnimationStart", insertListener, false); // IE
document.addEventListener("webkitAnimationStart", insertListener, false); // Chrome + Safari
"""
30byixjq

30byixjq5#

在Elm 0.19中,使用Browser.Dom.focus

import Browser.Dom as Dom
import Task

type Msg
    = NoOp

focusSearchBox : Cmd Msg
focusSearchBox =
    Task.attempt (\_ -> NoOp) (Dom.focus "search-box")

如果聚焦失败,您可以选择忽略(如上文所述),或者通过触发更新消息来执行操作。

ljsrvy3e

ljsrvy3e6#

Elm 0.19的Browser.Dom.focus是现代解决方案

import Browser.Dom as Dom
import Task

type Msg
    = NoOp
    | Focus String

focusElement : String -> Cmd Msg
focusElement htmlId =
    Task.attempt (\_ -> NoOp) (Dom.focus htmlId)

update : Msg -> Model -> (Model, Cmd Msg)
update msg =
    case msg of
        Focus htmlId ->
            ( model, focusElement htmlId )
        NoOp ->
            ( model, Cmd.none )

相关问题