2017-01-11 8 views
1

Мне бы хотелось узнать атрибут html элемента в Elm, например, ее координаты. Я пытался с Json.Decode.Я хотел бы узнать атрибут html элемента в Elm

Я новичок в Elm, и это предназначено для обучения.

Это простой код, я использую Elm 0.18:

module Stamps exposing (..) 

import Html exposing (..) 
import Html.Attributes exposing (..) 
import Html.Events exposing (..) 


type alias Model = 
    {} 


type Msg 
    = NoOp 
    | Clicking 


model : Model 
model = 
    {} 


update : Msg -> Model -> (Model, Cmd Msg) 
update msg model = 
    case msg of 
     NoOp -> 
      (model, Cmd.none) 

     Clicking -> 
      let 
       _ = 
        Debug.log "msg1" model 
      in 
       (model, Cmd.none) 


view : Model -> Html Msg 
view model = 
    div 
     [ Html.Attributes.style 
      [ ("backgroundColor", "blue") 
      , ("height", "300px") 
      , ("width", "300px") 
      , ("position", "relative") 
      , ("left", "100px") 
      , ("top", "50px") 
      ] 
     , Html.Attributes.class 
      "parent" 
     ] 
     [ div 
      [ Html.Attributes.style 
       [ ("background-color", "#3C8D2F") 
       , ("cursor", "move") 
       , ("width", "100px") 
       , ("height", "100px") 
       , ("border-radius", "4px") 
       , ("position", "absolute") 
       , ("color", "white") 
       , ("display", "flex") 
       , ("align-items", "center") 
       , ("justify-content", "center") 
       ] 
      , Html.Attributes.class 
       "children" 
      , Html.Events.onClick Clicking 
      ] 
      [] 
     ] 


subscriptions : Model -> Sub Msg 
subscriptions model = 
    Sub.none 


main : Program Never Model Msg 
main = 
    Html.program 
     { init = (model, Cmd.none) 
     , update = update 
     , view = view 
     , subscriptions = subscriptions 
     } 

ответ

6

Так что я не совсем уверен, какой из зачетов вы пытаетесь получить конкретно, но я думаю, что это поставит вы на ходу. Сначала вам нужно настроить клик для Msg ADT, чтобы иметь кортеж для координат.

type Msg 
    = NoOp 
    | Clicking (Int, Int) 

Предполагая, что вы хотите придерживаться только регистрации коордов, вы можете использовать это. Помните, что вы можете разрушить шаблон, если вам нужно.

update : Msg -> Model -> (Model, Cmd Msg) 
update msg model = 
    case msg of 
     NoOp -> 
      (model, Cmd.none) 

     Clicking cs -> 
      let 
       _ = 
        Debug.log "coords" cs 
      in 
       (model, Cmd.none) 

Вам нужен Json.Decode.Decoder к этому кортежу.

import Json.Decode as Decode exposing (Decoder) 


coordsDecoder : Decoder (Int, Int) 
coordsDecoder = 
    Decode.field "target" <| 
     Decode.map2 (,) 
      (Decode.field "offsetWidth" Decode.int) 
      (Decode.field "offsetHeight" Decode.int) 

И, наконец, вам нужно on взять декодер сделать что-то с Event объекта, возвращенного клик события JavaScript. Этот декодер получает координаты, затем Decode.map s Clicking msg type.

Html.Events.on "click" (Decode.map Clicking coordsDecoder) 

С этой Decode.field "target" ... вы можете начать декодирование, что вы хотите от целевого элемента.


Стилистически, вы импортируете все Html.* функций в сферу с exposing (..), но вы все еще предваряя все, что является довольно излишним. Вы можете использовать только style вместо Html.Attributes.style. Не бойтесь использовать as ->Html.Attributes as Attr.

0

Отличный ответ, если я попытаюсь получить координаты относительно браузера, в случае, если стиль слева и сверху не определен. Я ищу какое-то решение и нашел этот

offsetParent : a -> Decoder a -> Decoder a 
 
offsetParent x decoder = 
 
    Decode.oneOf 
 
    [ field "offsetParent" <| Decode.null x 
 
    , field "offsetParent" decoder 
 
    ]

 Смежные вопросы

  • Нет связанных вопросов^_^