Javascript 获取发生鼠标单击的html元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5181635/
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
Get html element in which a mouse click occurred?
提问by Richard H
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.
在 javascript 中,我希望能够确定发生鼠标单击的 html 页面中的元素。请注意,元素不会附加事件侦听器。
Basically: cursor somewhere in page, user clicks mouse, capture mouse click event, get element in which click occurred. Is this possible?
基本上:页面中某处的光标,用户单击鼠标,捕获鼠标单击事件,获取发生单击的元素。这可能吗?
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.
我想到的一种方法是获取点击事件的 x,y 坐标,遍历 DOM 获取每个元素的位置,并找到包含点击事件的最里面的元素。不过听起来有点啰嗦——所以想知道是否有另一种方式。
回答by Felix Kling
http://www.quirksmode.orgis a very nice website that explains a lot about events.
http://www.quirksmode.org是一个非常好的网站,它解释了很多关于事件的信息。
Especially for your question: Event properties - Which HTML element is the target of the event?.
特别是对于您的问题:事件属性 - 哪个 HTML 元素是事件的目标?.
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].
在 Internet Explorer 中,您可以event
使用event.srcElement
[docs]从对象中获取元素,而在所有其他浏览器中使用event.target
[docs]获取元素。
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).
另请参阅我链接到的示例中的“Safari 错误”解决方法(尽管我不知道它是否仍然存在和/或在什么版本的 Safari 中)。
回答by Douglas
Try event.target. There is an example on that page which shows how to use it.
试试event.target。该页面上有一个示例,显示了如何使用它。