如何阅读contentEditable div的内容?

时间:2016-05-14 19:36:56

标签: elm

我使用contentEditable div,我想在用户修改它之后访问其内容(onBlur)。如何访问DOM元素的innerHtml或textContent?有什么想法吗?

这是一个简单的例子:

import Html exposing (div, text)
import Html.App exposing (beginnerProgram)
import Html.Events exposing (onBlur)
import Html.Attributes exposing (contenteditable)


main =
  beginnerProgram { model = "Hello", view = view, update = update }


view model =
  div [contenteditable True, onBlur (SaveInput)] [ text model ]


type Msg = SaveInput


update msg model =
  case msg of
    SaveInput ->
      "ok"

我希望使用textContent将公式替换为“ok”以获取用户输入的值。我正在使用elm v 0.17。

2 个答案:

答案 0 :(得分:8)

这是一种方法。 您必须使用Json.Decode从事件对象中提取值。

import Html exposing (Html, div, text)
import Html.App exposing (beginnerProgram)
import Html.Events exposing (onBlur, on)
import Html.Attributes exposing (contenteditable, id)
import Json.Decode as Json
import Debug

main : Program Never
main = beginnerProgram { model = "Hello" , view = view , update = update }

type alias Model = String

view : Model -> Html Msg
view model =
  div [ contenteditable True ,on "blur" (Json.map SaveInput     targetTextContent)]
    [ text model ]

targetTextContent : Json.Decoder String
targetTextContent =
  Json.at ["target", "textContent"] Json.string

type Msg = SaveInput String

update : Msg -> Model -> Model
update msg model =
  case msg of
    SaveInput str -> (Debug.log "saving" str)

答案 1 :(得分:0)

我使用Dom.focus将Tosh的答案与一些额外的用户帮助相结合,以便在点击要编辑的元素后,光标变得可见。

update ... = 
        EditTitle ->
            ( model | editTitle = True }
            , Dom.focus "view-title" |> Task.attempt FocusResult
            )



viewNameEditor : Model -> Html Msg
viewNameEditor m =
    let
        attrs =
            if m.editTitle then
                    [ contenteditable True
                    , on "blur" (Json.map SaveViewName targetTextContent)
                    , id "view-title"
                    ]

            else
                    [ contenteditable False
                    , onClick EditTitle
                    , id "view-title"
                    ]
    in
        div attrs [ text current.name ]