【问题标题】:Get element width in ELM在 ELM 中获取元素宽度
【发布时间】:2021-05-29 09:04:49
【问题描述】:

我有喜欢的html

<h1 class = 'block__title' id='title'>Main text</h1>

用css:

.block__title {
  display: inline-block;
}

我可以通过以下方式在 js 中获取此元素:

const title = document.getElementById('title');

做任何宽度title.offsetWidth+1

我如何在 ELM 中做同样的事情? 我有:

[ h1 [ class "block-title" ]
            [ text (Main text)
            ]
]

我需要让元素的宽度更高以进行进一步的更改

【问题讨论】:

    标签: html elm


    【解决方案1】:

    你需要像这样使用Browser.Dom.getElement

    module Main exposing (main)
    
    import Browser
    import Browser.Dom exposing (Element, Error)
    import Html exposing (Html, button, div, h1, text)
    import Html.Attributes exposing (class, id)
    import Html.Events exposing (onClick)
    import Task
    
    
    type alias Model =
        { titleWidth : Float }
    
    
    init : () -> ( Model, Cmd Msg )
    init _ =
        ( { titleWidth = 0 }
        , Browser.Dom.getElement "title" |> Task.attempt GotElement
        )
    
    
    type Msg
        = GotElement (Result Error Element)
    
    
    update : Msg -> Model -> ( Model, Cmd Msg )
    update msg model =
        case msg of
            GotElement (Err err) ->
                ( model, Cmd.none )
    
            GotElement (Ok element) ->
                ( { model | titleWidth = element.element.width }, Cmd.none )
    
    
    view : Model -> Html Msg
    view model =
        div []
            [ h1 [ class "block-title", id "title" ] [ text "Main Title Text" ]
            , div [] [ text <| "Title Width: " ++ String.fromFloat model.titleWidth ]
            ]
    
    
    main : Program () Model Msg
    main =
        Browser.element
            { init = init
            , view = view
            , update = update
            , subscriptions = \_ -> Sub.none
            }
    

    您可以在getElement docs找到更多信息。

    【讨论】:

    • ty,它真的很有帮助,但我无法安装浏览器包,我得到了Your .elm/packages/ directory may be corrupted. I was led to believe that elm/browser existed, but I could not find anything when I went to look up the published versions of this package. 我的 json 是 ` "dependencies": { "elm/browser": "1.0.0
    • @Слава 您应该能够删除该目录并重建 - 我建议不要手动编辑 elm.json 文件 - 改用 elm install (这个包应该已经存在 - 可能作为一个隐藏的依赖 - 所以如果你可以在你已经拥有它之前编译你的项目)
    • @Carsten 我只使用elm install 但没有浏览器包我可以安装http、url-parser等,但不能安装浏览器包,看起来这个包不存在
    • 你使用的是什么版本(Elm)?
    • 是的,我想是的——事情发生了一些变化,但我在 0.18 核心库中找不到像 getElement 这样的东西
    猜你喜欢
    • 1970-01-01
    • 2018-08-12
    • 2011-06-08
    • 1970-01-01
    • 2013-08-11
    • 2015-10-17
    • 2010-12-10
    • 2014-06-24
    • 1970-01-01
    相关资源
    最近更新 更多