如何在 Elm 0.19 中监听全局鼠标事件?

How can I listen for global mouse events in Elm 0.19?

要在 Elm 中的 HTML 元素上监听鼠标事件,我们可以使用 Html.Events.onClick。但是,我想监听文档中任意位置的鼠标点击。

我找到了提供 Mouse.clickselm-lang/mouse 软件包,它似乎就是为此而设计的。在 Elm 0.18 上,可以这样安装:

elm-package install elm-lang/mouse

并像这样导入:

import Mouse exposing (clicks)

但是在 Elm 0.19 上,命令

elm install elm-lang/mouse

无效:

The following packages do not work with Elm 0.19.0 right now:

elm-lang/mouse

控制台输出中没有给出原因。 documentation 似乎没有表明此模块在版本 0.19 中发生了任何变化。

如何安装模块?或者,我如何使用 Elm 的标准库来全局监听鼠标点击(在文档上)?

包裹已 merged 变成 elm/browser。 因此,您现在使用 Browser.Events.onClick 而不是 Mouse.clicks。 请参阅浏览器包 here.

的文档

要检索鼠标位置,请使用 Json.Decode:

import Browser.Events exposing (onClick)
import Json.Decode as Decode

type alias Msg =
    { x : Int, y : Int }

subscriptions : Model -> Sub Msg
subscriptions model =
    onClick
        (Decode.map2 Msg
            (Decode.field "pageX" Decode.int)
            (Decode.field "pageY" Decode.int)
        )

有关其他属性,请参阅 MouseEvent 上的文档。

click and move 的快速在线演示。