在 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 中找到更多信息。