简体   繁体   English

如何判断鼠标是否悬停在元素上

[英]How to tell if a mouse is hovering over an element

Is there a function I can call to know if a certain element is currently being hovered over, like this? 是否有一个函数我可以调用,知道某个元素当前是否正在盘旋,像这样?

/* Returns true or false */
hoveringOver("a#mylink");

You can use jQuery's hover method to keep track: 您可以使用jQuery的hover方法来跟踪:

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

if ($(something).data('hover'))
    //Hovered!

Yes, in classic JS: 是的,在经典的JS中:

document.getElementById("mylink").onmouseover = function() { alert("Hover!"); }
document.getElementById("mylink").onmouseout  = function() { alert("Out!"); }

in jQuery: 在jQuery中:

$('#mylink').mouseover(function() {
  alert("Hover!");
});

I have no idea if this would be the best way to do this but if you are using jquery, you could do something like this: 我不知道这是否是最好的方法,但如果你使用jquery,你可以做这样的事情:

var hoveringOver = false;

$("a#myLink").bind("mouseenter", function(){
hoveringOver = true;
});

$("a#myLink").bind("mouseleave", function(){
hoveringOver = false;
});

function isHoveringOver(){
return hoveringOver;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM