Get element currently under mouse without using mouse events

前端 未结 1 899
臣服心动
臣服心动 2021-01-19 10:31

WRT building a Firefox Add-on.

Is it possible to get the element under the mouse via some XPCOM or javascript method? (non-js-ctypes please as that requires

相关标签:
1条回答
  • 2021-01-19 11:22

    I just looked through the source for code that gets (or stores and makes available) the cursor position. I didn't find anything one could use (from Javascript, XPCOM or not). I might have missed something... MXR is your friend.

    However, if you want to avoid mousemove (and this is a good idea in general), you can just look for the innermost hovered element, e.g. like so.

    function getInnermostHovered() {
        var n = document.querySelector(":hover");
        var nn;
        while (n) {
            nn = n;
            n = nn.querySelector(":hover");
        }
        return nn;
    }
    

    (fiddle demoing the principle)

    While this is what I'd consider a hack, it seems to work good enough most of the time, but will fail if the element has mouse events disabled via pointer-events. There could be other issues I didn't think of...

    Of course, this can return nothing when the document has no hovered element (e.g. the mouse is not actually within the document).

    0 讨论(0)
提交回复
热议问题