如何将焦点设置在Elm中的Html元素上?我试图在元素上设置autofocus属性,它只将焦点设置在页面加载上。
答案 0 :(得分:47)
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
答案 1 :(得分:9)
解决方法是使用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元素。
答案 2 :(得分:4)
我最近花了很多时间探索这个。不幸的是,我认为现有的elm-html
库不可能。然而,我想出了一个利用css动画触发事件并将其嵌入纯js的黑客攻击。
这是我在Elm中使用script
节点和style
节点的黑客攻击。我认为这非常难看。
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
"""
答案 3 :(得分:2)
使用elm / html 0.19,您可以将Html.Attrbutes autofocus设置为True
input [ onInput Code, autofocus True ] []
答案 4 :(得分:1)
在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")
您可以选择是否忽略聚焦失败,或者通过触发更新消息来执行某些操作。