获取发生鼠标点击的html元素? [英] Get html element in which a mouse click occurred?

查看:1018
本文介绍了获取发生鼠标点击的html元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中,我希望能够确定html页面中出现鼠标点击的元素。请注意,元素不会附加事件侦听器。

In javascript I'd like to be able to determine the element in the html page in which a mouse click occurs. Note that the elements will not have an event listener attached.

基本上:游标位于页面,用户点击鼠标,捕获鼠标点击事件,获取点击发生的元素。这是可能的吗?

Basically: cursor somewhere in page, user clicks mouse, capture mouse click event, get element in which click occurred. Is this possible?

我想到的一种方法是获取点击事件的x,y坐标,迭代DOM获取每个元素的位置,并找到包含点击事件的最内容的元素。听起来有点长时间了 - 所以想知道是否有另一种方式。

One approach I thought of is to get the x,y coords of the click event, iterate through the DOM getting the positions for each element, and finding the inner-most element which contains the click event. Sounds a bit long-winded though - so was wondering if there was another way.

推荐答案

https://www.quirksmode.org 是一个非常好的网站,它解释了很多有关事件。

http://www.quirksmode.org is a very nice website that explains a lot about events.

特别适用于您的问题: 事件属性 - 哪个HTML元素是事件的目标?

Especially for your question: Event properties - Which HTML element is the target of the event?.

在Internet Explorer中,您可以使用事件对象获取元素://msdn.microsoft.com/en-us/library/ms534638%28v=vs.85%29.aspx> event.srcElement [docs] 以及所有其他使用 event.target [docs]

In Internet Explorer, you can get the element from the event object with event.srcElement[docs] and in all other browsers with event.target[docs].

另见在我链接到的示例中的Safari bug解决方法(虽然我不知道它是否仍然存在和/或在什么版本的Safari )。

Also see the "Safari bug" workaround in the example I linked to (although I don't know whether it still exist and/or in what version of Safari).

这篇关于获取发生鼠标点击的html元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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