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.
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'); } } }
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('鼠标不在该DIV中'); }else{ alert('鼠标在该DIV中'); };
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!