【问题标题】:Accessing an element that is currently being hovered by mouse, from anywhere in the document [closed]从文档中的任何位置访问当前被鼠标悬停的元素[关闭]
【发布时间】:2014-03-12 10:21:27
【问题描述】:

有什么方法可以让我使用 jquery 访问当前鼠标悬停在其上的元素?

我知道我可以通过将mouseover 事件附加到一个元素来访问一个元素,但是当我没有对一个元素应用任何事件并且想要访问被鼠标悬停的那个特定元素时呢?从文档中的任何地方?

【问题讨论】:

  • 您的用例到底是什么?或者您为什么不想将事件附加到 DOM?
  • 鼠标悬停有什么问题?

标签: javascript jquery dom hover jquery-hover


【解决方案1】:

您可以将mouseover 事件附加到document 并使用event.target 获取当前悬停的元素。

试试,

$(document).mouseover(function(e){
  console.log($(e.target).attr('id')); // i just retrieved the id for a demo
});

【讨论】:

  • 将一直触发鼠标悬停事件,最好只有当您将鼠标悬停在元素上时才会触发事件。可能是这样的 $('body:not(:empty))'跨度>
【解决方案2】:
document.onmousemove = function (e) {
    e = e || window.event;
    evt = e;
}

使用 evt.target 获取元素

【讨论】:

  • 为什么要打扰evt = e 行?
  • @AnthonyGrist 我很久以前有一些原因,我现在不记得了,我想我有跨浏览器问题导致一些问题
  • 这里找到了一些参考 Internet Explorer provides a global object window.event, which references the last event. And before IE9 there are no arguments in the handler. javascript.info/tutorial/obtaining-event-object @AnthonyGrist
  • 这解释了第一行,我完全理解。我不明白的是为什么你将你已经拥有的东西存储在e 作为另一个变量evt,而实际上没有理由这样做;之后,您可以在代码中使用evt 的任何地方使用e
  • 好的,因此您打算将事件对象存储为全局(或至少更高范围的)变量,然后您可以在其他代码段中使用它。这就是我要寻找的解释。
【解决方案3】:

事件对象的目标属性可以帮助你。 例如:

$('button:first').mouseover(function(e){


   var target = (e.target) ? e.target: e.srcElement;
   console.log(target );// get element that is being hovered over right now

});

document.querySelectorAll('button')[0].onmouseover = function(e){

   var target = (e.target) ? e.target: e.srcElement;
   console.log(target);// get element that is being hovered over right now

};

当您想要获取注册到事件调度程序的元素时,您必须改用 currentTarget-attribute。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 2019-04-02
    • 2021-11-10
    • 2012-05-23
    相关资源
    最近更新 更多