检查鼠标是否在div内 [英] Check if mouse is inside div

查看:77
本文介绍了检查鼠标是否在div内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用if语句检查鼠标是否在某个div内,如下所示:

I want to use an if statement to check if the mouse is inside a certain div, something like this:

if ( mouse is inside #element ) {
 // do something
} else {
 return;
}

这将导致该函数在鼠标位于#element内部时启动,并在鼠标位于#element外部时停止.

This will result in the function to start when the mouse is inside #element, and stops when the mouse is outside #element.

推荐答案

您可以注册jQuery处理程序:

you can register jQuery handlers:

var isOnDiv = false;
$(yourDiv).mouseenter(function(){isOnDiv=true;});
$(yourDiv).mouseleave(function(){isOnDiv=false;});

没有jQuery替代品:

no jQuery alternative:

document.getElementById("element").addEventListener("mouseenter", function(  ) {isOnDiv=true;});
document.getElementById("element").addEventListener("mouseout", function(  ) {isOnDiv=false;});

和其他地方:

if ( isOnDiv===true ) {
 // do something
} else {
 return;
}

这篇关于检查鼠标是否在div内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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