如何将重点放在Elm中的元素上? [英] How to set focus on an element in Elm?

查看:119
本文介绍了如何将重点放在Elm中的元素上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将重点放在Elm中的Html元素上?我试图在元素上设置autofocus属性,并且它只设置了页面加载的焦点。

解决方案


焦点函数=noreferrer> elm-lang / dom 软件包用于设置焦点,使用任务(不使用任何 port s或JavaScript)。



它在内部使用 requestAnimationFrame ,以确保在尝试查找要关注的DOM节点之前呈现任何新的DOM更新。

一个使用示例: $ b

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

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

FocusResult结果 - >
- 在此处理成功或失败
结果为
Err(Dom.NotFound id) - >
- 无法找到dom'id'
Ok() - >
- 成功关注dom

艾莉的完整示例


How can I set the focus on a Html element in Elm? I tried to set the autofocus attribute on the element and it only sets the focus on the page load.

解决方案

The focus function in the elm-lang/dom package is used to set focus with a Task (without using any ports or JavaScript).

Internally it uses requestAnimationFrame to ensure any new DOM updates are rendered before it tries to find the DOM node to focus on.

An example use:

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

这篇关于如何将重点放在Elm中的元素上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆