如何知道鼠标指针是否在HTML元素上? [英] how do I know if the mouse pointer is on the HTML element?

查看:163
本文介绍了如何知道鼠标指针是否在HTML元素上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定时事件,我想要与鼠标指针所在的HTML元素有所不同。

假设我有HTML元素,有没有办法知道鼠标指针是否是

我非常了解onmouseover / onmouseout事件以及如何使用它们。

我正在使用JQuery。

我是明显地寻找某种标志,因为我需要检查一个状态,而不是处理一个事件。

再次,我知道如何用事件来实现这个。

I have a timed event I want to behave differently accordingly to what HTML element the mouse pointer is on.
Is there a way, assuming I have the HTML element, to know if the mouse pointer is currently on top of it.
I am well aware of the onmouseover/onmouseout events and how to use them.
I am using JQuery.
I am obviously looking for some kind of flag, as I need to check a state and not handle an event.
again, I know how to implement this with events.

推荐答案

我没有意识到任何内置的方法来ping一个元素的鼠标悬停状态。

I'm not aware of any built-in way to ping an element for the status of mouse hovering.

但是,您可以通过在mouseenter和mouseleave上更新标记来创建一个标记 - 这是 Brian Driscoll的建议 .hover 进入:

However, you can create one by updating a flag at mouseenter and mouseleave -- which is where Brian Driscoll's suggestion of .hover comes in:

jQuery.fn.tracking = function () {
  this.data('hovering', false);

  this.hover(function () {
    $(this).data('hovering', true);
  }, function () {
    $(this).data('hovering', false);
  });

  return this;
};

jQuery.fn.hovering = function () {
  return this.data('hovering');
}

您需要为您关心的每个元素初始化跟踪: p>

You'll need to initialize tracking for each element you care about:

$('#elem1,#elem2').tracking();

但是,您可以获得以下任何一种的状态:

But then you can get the status of any of them:

if ($('#elem1').hovering()) {
    // ...
} else if ($('#elem2').hovering()) {
    // ...
}

演示: http://jsbin.com/amaxu3/edit

这篇关于如何知道鼠标指针是否在HTML元素上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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