在Elm中,如何检测相对于html元素的鼠标位置?

时间:2017-09-19 16:53:32

标签: elm mousemove onmousemove

我想知道相对于html元素的鼠标位置。我也知道元素的大小。

1 个答案:

答案 0 :(得分:6)

可以使用mouseMove事件检测鼠标位置。这是如何使用The Elm Architecture实现它的一个例子。

观点:

view : Model -> Html Msg
view model =
    div []
        [ img
            [ on "mousemove" (Decode.map MouseMove decoder)
            , src "http://..."
            ]
            []
        ]

解码器:

decoder : Decoder MouseMoveData
decoder =
    map4 MouseMoveData
        (at [ "offsetX" ] int)
        (at [ "offsetY" ] int)
        (at [ "target", "offsetHeight" ] float)
        (at [ "target", "offsetWidth" ] float)

类型别名

type alias MouseMoveData =
    { offsetX : Int
    , offsetY : Int
    , offsetHeight : Float
    , offsetWidth : Float
    }

和消息

type Msg
    = MouseMove MouseMoveData

这就是数据到达更新的方式:

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        MouseMove data ->
            -- Here you can use your "data", updating
            -- the model with it, for example
            ( { model | zoomMouseMove = Just data }, Cmd.none )

这是一个执行类似操作的库:http://package.elm-lang.org/packages/mbr/elm-mouse-events/1.0.4/MouseEvents