每10毫秒检查鼠标是否仍在元素上徘徊的函数(如果存在,则运行一个函数) [英] A Function to Check if the Mouse is Still Hovering an Element Every 10 Milliseconds (and run a function if it is)

查看:89
本文介绍了每10毫秒检查鼠标是否仍在元素上徘徊的函数(如果存在,则运行一个函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否在某个元素(例如div class ="myiv")悬停后是否要运行一个函数,并每隔X毫秒检查一次是否仍在悬停,如果是,则运行另一个函数.

I was wondering if there is a function to be run after an element (e.g. div class="myiv") is hovered and check every X milliseconds if it's still hovered, and if it is, run another function.

这对我有用: http://jsfiddle.net/z8yaB/

推荐答案

对于大多数目的,在简单的界面中,您可以使用jquery的悬停功能,并且只要将鼠标悬停在布尔值中即可.然后,您可以使用简单的setInterval循环在每个ms中检查此状态.您还可以在第一个评论中的链接重复项中找到此答案(,现在在此处其他答案中).

For most purposes in simple interfaces, you may use jquery's hover function and simply store in a boolean somewhere if the mouse is hover. And then you may use a simple setInterval loop to check every ms this state. You yet could see in the first comment this answer in the linked duplicate (edit : and now in the other answers here).

但是在某些情况下,尤其是当鼠标悬停时,当对象在鼠标和对象之间移动"时,会产生错误警报.

But there are cases, especially when you have objects moving "between" the mouse and your object when hover generate false alarms.

在这种情况下,我制作了此函数,以检查jquery调用我的处理程序时事件是否真的在元素上悬停了:

For those cases, I made this function that checks if an event is really hover an element when jquery calls my handler :

var bubbling = {};
bubbling.eventIsOver = function(event, o) {
if ((!o) || o==null) return false;
var pos = o.offset();
var ex = event.pageX;
var ey = event.pageY;
if (
    ex>=pos.left
    && ex<=pos.left+o.width()
    && ey>=pos.top
    && ey<=pos.top+o.height()
) {
    return true;
}
return false;
};

当我收到mouseout事件时,我使用此功能来检查鼠标是否真的离开了:

I use this function to check that the mouse really leaved when I received the mouseout event :

 $('body').delegate(' myselector ', 'mouseenter', function(event) {
    bubbling.bubbleTarget = $(this);

    // store somewhere that the mouse is in the object

}).live('mouseout', function(event) {
    if (bubbling.eventIsOver(event, bubbling.bubbleTarget)) return;

    // store somewhere that the mouse leaved the object

});

这篇关于每10毫秒检查鼠标是否仍在元素上徘徊的函数(如果存在,则运行一个函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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