简体   繁体   English

如何检测鼠标是否在 jQuery 或 Javascript 中的项目上

[英]How to detect if mouse is over an item in jQuery or Javascript

Is it possible to check if the cursor is over an item?是否可以检查 cursor 是否超过一个项目? In my case I can't use focus(), mouseenter() or any of the related methods but I just need to find out if the mouse is over it.在我的情况下,我不能使用 focus()、mouseenter() 或任何相关方法,但我只需要找出鼠标是否在它上面。

Instead of checking the state of the mouse, in this particular case you could create a transparent overlay element on top of the one you want to hide.无需检查鼠标的 state,在这种特殊情况下,您可以在要隐藏的元素之上创建一个透明覆盖元素。

So as that when the area is hovered it shows and when it's not it gets hidden obviously setting the element that is to be hidden (until hovered) with a default display: none;因此,当该区域悬停时,它会显示,而当它不显示时,它显然会被隐藏,将要隐藏的元素(直到悬停)设置为默认显示:无; in your css - therefore it only shows when hovered, to the users eye.在您的 css 中- 因此它仅在用户眼中悬停时显示。

I know it's not what the OP was asking for but it works.我知道这不是 OP 所要求的,但它有效。

$(document).ready(function(){
    /* 
    * #object is your element you 
    * want to hide unless hovered
    */
    $("#object").on("mouseleave", function(){
        // divs you want to hide/show
        $('#object').hide();
        $('#overlay').show();
    })

    /* 
    * #overlay is the transparent element 
    * that will sit over the top of #object
    */
    $("#overlay").on("mouseenter", function(){
        // divs you want to hide/show
        $('#object').show();
        $('#overlay').hide();
    })
});

see it working here http://jsfiddle.net/si_jsfiddle/CvkyE/看到它在这里工作http://jsfiddle.net/si_jsfiddle/CvkyE/

This is a good option because mouseenter and mouseleave aren't affected by objects on top of them especially with out the tag object parameter set in the on() method, this is also why they're great for div containers with links on top etc...这是一个不错的选择,因为 mouseenter 和 mouseleave 不受它们顶部的对象的影响,尤其是在 on() 方法中没有设置标签 object 参数的情况下,这也是为什么它们非常适合带有顶部链接的 div 容器等...

Could this be useful?这有用吗? event.target事件.目标

fiddle DEMO小提琴演示

Ex:前任:

function handler(ev) {
  var $target = $(ev.target);
  if( $target.is("#element") ) {
   alert('Here am I !');
  }
}
$("#element").hover(handler);

And here is a slight modification to remove element这是删除元素的轻微修改

demo演示

function handler(ev) {
  var $target = $(ev.target);
  if( $target.is("#element") ) {
         $target.remove();
  }
}
$("#element").mouseleave(handler);

http://api.jquery.com/mouseover/ here is the jquery function. http://api.jquery.com/mouseover/这里是 jquery ZC1C4145268E47A98 It has a good example too.它也有一个很好的例子。

<input etc.... onmouseover="if (condition){calltoafunction();"}>

On Javascript:If the Cursor is over an Item then if condition work.在 Javascript 上:如果 Cursor 超过一个项目,那么如果条件工作。

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

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