2017-01-11 33 views
1

我想知道Elm中元素的屬性html,例如她的座標。我正在嘗試使用Json.Decode。我想知道Elm中元素的屬性html

我是新來的榆樹,這是爲了學習的目的。

這是一個簡單的代碼,我使用榆木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採取解碼器做一個JavaScript的點擊事件返回的Event對象的東西。這個解碼器獲取座標,然後是 s的Clicking msg類型。

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 
 
    ]