javascript 在Javascript中,如何获取鼠标指针所在div的当前ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3960376/
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
In Javascript, how to get the current id of the div where mouse pointer is?
提问by svirk
How to get the id of the div on which the mouse is currently pointing?
如何获取鼠标当前指向的div的id?
回答by lincolnk
I think your best bet is to track mouseoverat the documentlevel and maintain the id of the last element hit.
我认为最好的方法是跟踪mouseover的document水平,并保持最后一个元素命中的ID。
var lastID = null;
var handleMouseover = function (e) {
var target = e.target || e.srcElement;
lastID = target.id;
};
if (document.addEventListener) {
document.addEventListener('mouseover', handleMouseover, false);
}
else {
document.attachEvent('onmouseover', handleMouseover);
}
回答by Fosco
You can use a javascript variable to store the current hovered div.. jQuery (or standard JS) could be used to set the event handler to populate the variable.
您可以使用 javascript 变量来存储当前悬停的 div .. jQuery(或标准 JS)可用于设置事件处理程序以填充变量。
Visible test at: http://jsfiddle.net/gfosco/Hys7r/
回答by Alberto Zaccagni
<div id="the-id" onmouseover="alert(this.id)">some text</div>

