html - 在 Elm 中使用 Color 对象更改 HTML 元素颜色的标准方法是什么?

标签 html elm

我刚开始学习 Elm,不知何故找不到任何将颜色应用于 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 以外的东西吗?在这里,因为它需要一个 (String, String) 元组列表?或者我只是没有找到正确的类型转换函数?

(编辑代码以包含模型)

最佳答案

颜色 - 或任何其他样式属性,如大小、边框、字体等 - 可以使用 style from Html.Attributes 应用于 Elm Html 元素。 (将单独的样式应用于元素)或使用 class from the same package (将具有多种样式的 css 类应用于一个元素)。

哪个是标准取决于您的具体用例。我建议:

  • 如果它真的是静态的(颜色永远不会改变),请使用 CSS。
  • 如果颜色是一组样式元素的一部分,用于显示某个按钮是否启用或交替显示列表中的颜色,请使用 CSS。
  • 如果颜色确实具有交互性,例如用户可以从调色板或 slider 中进行选择,使用样式。

有关样式的文档包括有关背景颜色的示例。

myStyle : Attribute msg
myStyle =
  style
    [ ("backgroundColor", "red")
    , ("height", "90px")
    , ("width", "100%")
    ]

greeting : Html msg
greeting =
  div [ myStyle ] [ text "Hello!" ]

下面(可复制到 elm-lang.org/try )是一个改变颜色的例子。

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"

关于html - 在 Elm 中使用 Color 对象更改 HTML 元素颜色的标准方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40297054/

相关文章:

html - 翻转箭头字符

elm - Elm 中解码超过 8 个字段的对象

dom - 如何在 Elm 中使用 Window.dimensions 初始化模型?

elm - 带有和不带有 (..) 的 Elm 中的模块导入

functional-programming - 具有相同字段的两条记录的模式匹配

html - 不允许嵌套函数

html - 标签后面的单词的 XPath?

Vim + elm-vim 无法识别 .elm 文件

javascript - 在列表之间绘制箭头

javascript - 提高生成 HTML 表格的速度