在 ELM 中获取元素宽度

Get element width in ELM

我有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)
            ]
]

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

您需要像这样使用 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 中找到更多信息。