Home > Web Front-end > JS Tutorial > body text

How to determine if the mouse is inside an element with jQuery

coldplay.xixi
Release: 2023-01-04 09:38:12
Original
7567 people have browsed it

How jQuery determines whether the mouse is within an element: 1. Determine whether the mouse is in the first-level menu. If it is not in the first-level menu, whether it is in the second-level menu; 2. Jquery obtains the mouse position and determines the mouse Whether it is in a DIV.

How to determine if the mouse is inside an element with jQuery

The operating environment of this tutorial: windows7 system, jquery3.2.1 version, DELL G3 computer.

Recommended: jquery video tutorial

##How to determine whether the mouse is within an element using jQuery:

Method 1:

Take the page header as an example:

(Judge whether the mouse is in the first-level menu, if not menu, whether it is in the secondary menu)

$('#header').mousemove(function(e){
    if($.contains($("#navUl")[0],e.target) || $("#navUl")[0]==e.target){
        // console.log('在menu中')
    }else{
        // console.log('不在menu中');
        if($.contains($("#submenu")[0],e.target) || $("#submenu")[0]==e.target){
            // console.log('在二级menu中')
        }else{
            // console.log('不在二级menu中');
            $("#navUl>li").removeClass('active');
        }
    }
    
}
Copy after login

Method 2: Traditional method: Jquery gets the mouse position and determines whether the mouse is in the DIV

$(document).mousemove(function(e){ 
     x = e.pageX;
         y = e.pageY; 
});
 
//x的值相对于文档的左边缘。y的值相对于文档的上边缘
//x,y是全局变量;
//判断鼠标是否在某DIV中
var div = $('.dream');//获取你想要的DIV
var y1 = div.offset().top;  //div上面两个的点的y值
var y2 = y1 + div.height();//div下面两个点的y值
var x1 = div.offset().left;  //div左边两个的点的x值
var x2 = x1 + div.width();  //div右边两个点的x的值
 
if( x < x1 || x > x2 || y < y1 || y > y2){
    alert(&#39;鼠标不在该DIV中&#39;);
}else{
    alert(&#39;鼠标在该DIV中&#39;);
};
Copy after login

Related free learning recommendations: javascript video tutorial

The above is the detailed content of How to determine if the mouse is inside an element with jQuery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!