Javascript 在Javascript中确定鼠标指针位于哪个元素之上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8813051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:38:35  来源:igfitidea点击:

Determine which element the mouse pointer is on top of in Javascript

javascriptdommouse

提问by Tom Lehman

I want a function that tells me which element the mouse cursor is over.

我想要一个函数来告诉我鼠标光标在哪个元素上。

So, for example, if the user's mouse is over this textarea (with id wmd-input), calling window.which_element_is_the_mouse_on()will be functionally equivalent to $("#wmd-input")

因此,例如,如果用户的鼠标悬停在此文本区域(带有 id wmd-input)上,则调用window.which_element_is_the_mouse_on()在功能上等同于$("#wmd-input")

回答by qwertymk

DEMO

演示

There's a really cool function called document.elementFromPointwhich does what it sounds like.

有一个非常酷的函数叫做document.elementFromPoint它听起来像什么。

What we need is to find the x and y coords of the mouse and then call it using those values:

我们需要的是找到鼠标的 x 和 y 坐标,然后使用这些值调用它:

var x = event.clientX, y = event.clientY,
    elementMouseIsOver = document.elementFromPoint(x, y);

document.elementFromPoint

document.elementFromPoint

jQuery event object

jQuery 事件对象

回答by dherman

In newer browsers, you could do the following:

在较新的浏览器中,您可以执行以下操作:

document.querySelectorAll( ":hover" );

That'll give you a NodeList of items that the mouse is currently over in document order. The last element in the NodeList is the most specific, each preceding one should be a parent, grandparent, and so on.

这将为您提供鼠标当前按文档顺序悬停的项目的 NodeList。NodeList 中的最后一个元素是最具体的,前面的每个元素都应该是父级、祖父级等等。

回答by herrlich10

Although the following may not actually answering the question, since this is the first result of googling (the googler may not asking exactly the same question:), hope it will provide some extra input.

虽然以下内容可能实际上并没有回答问题,因为这是谷歌搜索的第一个结果(谷歌人可能不会问完全相同的问题:),希望它能提供一些额外的输入。

There are actually two different approaches to get a list of all elements the mouse is currently over (for newer browsers, perhaps):

实际上有两种不同的方法来获取鼠标当前所在的所有元素的列表(对于较新的浏览器,也许):

The "structual" approach - Ascending DOM tree

“结构化”方法 - 升序 DOM 树

As in dherman's answer, one can call

正如在 dherman 的回答中,人们可以打电话

var elements = document.querySelectorAll(':hover');

However, this assumes that only children will overlay their ancestors, which is usually the case, but not true in general, especially when dealing with SVG where element in different branches of the DOM tree may overlap each other.

然而,这假设只有孩子会覆盖他们的祖先,这通常是这种情况,但一般情况下并非如此,尤其是在处理 SVG 时,其中 DOM 树的不同分支中的元素可能相互重叠。

The "visual" approach - Based on "visual" overlapping

“视觉”方法——基于“视觉”重叠

This method uses document.elementFromPoint(x, y)to find the topmost element, temporarily hide it (since we recover it immediately in the same context, the browser will not actually renders this), then go on to find the second topmost element... Looks a little hacky, but it returns what you expect when there are, e.g., siblings elements in a tree occluding each other. Please find this postfor more details,

该方法用于document.elementFromPoint(x, y)查找最顶层元素,暂时隐藏它(因为我们在同一上下文中立即恢复它,浏览器实际上不会渲染它),然后继续查找第二个最顶层元素......看起来有点hacky,但是当树中存在相互遮挡的兄弟元素时,它会返回您期望的内容。请找到这篇文章以获取更多详细信息,

function allElementsFromPoint(x, y) {
    var element, elements = [];
    var old_visibility = [];
    while (true) {
        element = document.elementFromPoint(x, y);
        if (!element || element === document.documentElement) {
            break;
        }
        elements.push(element);
        old_visibility.push(element.style.visibility);
        element.style.visibility = 'hidden'; // Temporarily hide the element (without changing the layout)
    }
    for (var k = 0; k < elements.length; k++) {
        elements[k].style.visibility = old_visibility[k];
    }
    elements.reverse();
    return elements;
}

Try both, and check their different returns.

尝试两者,并检查它们的不同回报。

回答by Karl Adler

elementFromPoint()gets only the first element in DOM tree. This is mostly NOT enough for developers needs. To get more than one element at e.g. current mouse pointer position this is the function you need:

elementFromPoint()只获取 DOM 树中的第一个元素。这对于开发人员的需求来说大多是不够的。要在当前鼠标指针位置获取多个元素,这是您需要的功能:

document.elementsFromPoint(x, y) . // mind the 's' in elements

This returns an array of all element objects under the given point. Just pass the mouse X and Y values to this function.

这将返回给定点下所有元素对象的数组。只需将鼠标 X 和 Y 值传递给此函数。

More info here: https://developer.mozilla.org/en-US/docs/Web/API/document/elementsFromPoint

更多信息:https: //developer.mozilla.org/en-US/docs/Web/API/document/elementsFromPoint

For very old browsers which are not supported, you may use this answeras a fallback.

对于不支持的非常旧的浏览器,您可以使用此答案作为后备。

回答by saikumar

The following code will help you to get element of mouse pointer. Resulted elements will display in console.

以下代码将帮助您获取鼠标指针元素。结果元素将显示在控制台中。

document.addEventListener('mousemove', function(e) {
    console.log(document.elementFromPoint(e.pageX, e.pageY)); 
})

回答by RobG

Mouseover events bubble, so you can put a single listener on the body and wait for them to bubble up, then grab the event.targetor event.srcElement:

鼠标悬停事件冒泡,因此您可以在主体上放置一个侦听器并等待它们冒泡,然后抓住event.targetor event.srcElement

function getTarget(event) {
    var el = event.target || event.srcElement;
    return el.nodeType == 1? el : el.parentNode;
}

<body onmouseover="doSomething(getTarget(event));">

回答by Ry-

You can look at the target of the mouseoverevent on some suitable ancestor:

您可以mouseover在一些合适的祖先上查看事件的目标:

var currentElement = null;

document.addEventListener('mouseover', function (e) {
    currentElement = e.target;
});

Here's a demo.

这是一个演示。

回答by Dip M

<!-- One simple solution to your problem could be like this: -->

<div>
<input type="text" id="fname" onmousemove="javascript: alert(this.id);" />
<!-- OR -->
<input type="text" id="fname" onclick="javascript: alert(this.id);" />
</div>
<!-- Both mousemove over the field & click on the field displays "fname"-->
<!-- Works fantastic in IE, FireFox, Chrome, Opera. -->
<!-- I didn't test it for Safari. -->

回答by Zibri

DEMO :D Move your mouse in the snippet window :D

演示 :D 在代码片段窗口中移动鼠标 :D

<script>
document.addEventListener('mouseover', function (e) {
   console.log ("You are in ",e.target.tagName);
});
</script>

回答by Serge Gordeev

You can use this selector to undermouse object and than manipulate him as jquery object. $(':hover').last();

您可以使用此选择器将对象置于鼠标下方,而不是将其作为 jquery 对象进行操作。 $(':hover').last();