我刚刚开始学习榆树,并且无法找到任何将颜色应用于div elm-lang/html
或elm-lang/color
import Html exposing (Html, div)
import Html.Attributes exposing (style)
import Html.Events exposing (onClick)
import Color
type alias Model = {
color : Color.Color
}
view : Model -> Html Msg
view model =
div
[
[ onClick ChangeColor ] ,
[ style
( "background-color" model.color ??? ),
( "height", "200" ),
( "width", "500" ),
]
]
[]
我是否应该使用style
以外的其他内容,因为它需要List(String,String)元组?或者我只是没有为类型转换找到合适的函数?
(包含模型的编辑代码)
答案 0 :(得分:4)
颜色 - 或任何其他样式属性,如大小,边框,字体等等 - 可以使用style from Html.Attributes(将单个样式应用于元素)或使用{{3]应用于Elm Html元素(将具有多个样式的css类应用于元素)。
哪个标准取决于您的具体用例。我建议:
关于样式的文档包含背景颜色的示例。
myStyle : Attribute msg
myStyle =
style
[ ("backgroundColor", "red")
, ("height", "90px")
, ("width", "100%")
]
greeting : Html msg
greeting =
div [ myStyle ] [ text "Hello!" ]
下面(可复制到class from the same package)是一个关于改变颜色的例子。
import Html exposing (div, button, text)
import Html.App exposing (beginnerProgram)
import Html.Events exposing (onClick)
import Html.Attributes exposing (style)
type alias Model = String
init = "blue"
main =
beginnerProgram { model = init, view = view, update = update }
view model =
let
myStyle =
[ ( "width", "200px" )
, ( "height", "200px" )
, ( "backgroundColor", model )
]
in
div [ style myStyle ]
[ button [ onClick ChangeColor ] [ text "Change color" ]
]
type Msg = ChangeColor
update msg model =
case msg of
ChangeColor ->
case model of
"blue" -> "red"
"red" -> "orange"
"orange" -> "blue"
_ -> "blue"
答案 1 :(得分:1)
我发现这个[elm-color-extra] [1]包有几个Convert工具。这个诀窍,但是我现在要把这个问题留下来,以防万一这样做的方式更加愚蠢。
这是我的最终计划(在我项目的顶级文件夹中elm package install eskimoblood/elm-color-extra
之后)。它是一个正方形,当您点击它时会变为随机颜色:
module ColorSquare exposing (..)
import Html exposing (Html, div)
import Html.Attributes exposing (style)
import Html.Events exposing (onClick)
import Html.App
import Color
import Color.Convert
import Random
-- Model
type alias Model = {
color : Color.Color,
seed : Random.Seed
}
init : ( Model, Cmd Msg )
init =
(
{color = Color.rgb 0 255 0, seed = Random.initialSeed 1234 },
Cmd.none
)
-- Messages
type Msg = ChangeColor
-- View
view : Model -> Html Msg
view model =
div
[
( onClick ChangeColor ) ,
( style [
(
"background-color",
Color.Convert.colorToCssRgb model.color
),
( "height", "200px" ),
( "width", "500px" )
]
)
]
[]
-- Update
randomColor : Random.Generator Color.Color
randomColor =
Random.map3 Color.rgb (Random.int 0 255) (Random.int 0 255) (Random.int 0 255)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
ChangeColor ->
let
(color, seed) = Random.step randomColor model.seed
in
({color = color, seed = seed} , Cmd.none )
-- Subscriptions
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- Main
main : Program Never
main =
Html.App.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}