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

Luc*_*mug 2 onmousemove mousemove elm

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

Luc*_*mug 6

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

风景:

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

解码器:

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

别名

type alias MouseMoveData =
    { offsetX : Int
    , offsetY : Int
    , offsetHeight : Float
    , offsetWidth : Float
    }
Run Code Online (Sandbox Code Playgroud)

和消息

type Msg
    = MouseMove MouseMoveData
Run Code Online (Sandbox Code Playgroud)

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

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 )
Run Code Online (Sandbox Code Playgroud)

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