获取当前鼠标下的元素,而不使用鼠标事件 [英] Get element currently under mouse without using mouse events

查看:181
本文介绍了获取当前鼠标下的元素,而不使用鼠标事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WRT构建一个Firefox附加组件。

是否可以通过一些XPCOM或JavaScript方法获取鼠标下的元素? (非js-ctypes,因为这需要操作系统的特殊性)

我想要检测当用户按下 Ctrl + Shift + M

现在我添加一个<$ c $当用户按下这个热键时,鼠标悬停在鼠标上,当鼠标移动时,鼠标可以在鼠标下,但是当鼠标按下热键组合。

解决方案

我只是通过源代码来获取(或存储并使其可用)的光标位置。我没有找到任何可以使用的东西(从Javascript,XPCOM或不)。我可能错过了一些... MXR 是你的朋友。


$ b $然而,如果你想避免 mousemove (这通常是一个好主意),你可以只查找最内层的元素,例如像这样。

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



虽然这是我认为的一个破解,但它似乎工作足够好大部分的时间,但如果元素通过 指针事件 。可能还有其他问题,我没有想到...

当然,当文档没有悬停的元素时,它可以不返回任何东西(例如,鼠标不是实际的在文件内)。

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 OS specificity)

I want to detect what is under the mouse when user presses Ctrl + Shift + M.

Right now I'm adding a mouseover listener to the document when the user presses this hotkey, so I can get the element under the mouse when he moves it, but not the element that was under the mouse exactly when he pressed the hotkey combination.

解决方案

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).

这篇关于获取当前鼠标下的元素,而不使用鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆