[英]Detect if the mouse is over an element
How do I get a pretty simple true/false-statement if the mouse is over a div event = true else event = false 如果鼠标悬停在div上,如何获得非常简单的true / false语句event = true else event = false
var test = $("#main-nav").on("mouseenter", function (e) {
e.preventDefault();
console.log(e.preventDefault());
return true;
});
if (test === true) {
//do something
} else {
//something different
}
If I understand your question correctly: 如果我正确理解您的问题:
if($("#main-nav").is(":hover")) {
//do something
}else{
//something different
}
In pseudo code: 用伪代码:
if the cursor is over #main-nav
do something
if it's not
do something else
If you want test
to always be set: 如果要始终设置test
:
var test = false;
$("#main-nav").on("mouseenter", function(e){
e.preventDefault();
test = true;
}).on("mouseleave", function(e){
e.preventDefault();
test = false;
});
This way, 这条路,
if(test === true) {
//do something
}else{
//something different
}
will always work. 将始终有效。
You can have a boolean ( true
/ false
) variable that will constantly update by doing this: 您可以使用以下布尔值( true
/ false
)进行不断更新:
var hovering;
$("#main-nav").mouseenter(function(){
hovering = true;
});
$("#main-nav").mouseleave(function(){
hovering = false;
});
So whenever it is called it will tell you if the mouse is within your div: 因此,无论何时调用它,它都会告诉您鼠标是否在div内:
if (hovering){
// mouse within div
} else {
// mouse not within div
}
If you necessarily need is as a variable: 如果您确实需要将其作为变量:
var test = false;
$("#main-nav").on("mouseenter", function (e) {
test = true;
});
$("#main-nav").on("mouseout", function (e) {
test = false;
});
//....
if (test === true) {
//do something
} else {
//something different
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.