Home >Web Front-end >JS Tutorial >jQuery realizes the effect of closing the pop-up layer by clicking anywhere outside the pop-up layer
When I was working on projects before, I would often click a button on the main page, and a div would pop up on the right to output detailed information about the corresponding content. At this time, I hope to close the pop-up layer when the mouse clicks outside the pop-up layer. The main idea is:
Find the element clicked by the mouse
To determine whether this element is within the specified area, in fact, it is to determine its parent element Is it a pop-up layer?
If not, hide the pop-up layer. If it is, no operation will be performed.
Specific implementation
This code requires the use of jQuery. The code is as follows:
$(document).mousedown(function(e){ if($(e.target).parent("#info").length==0){ $("#info").hide(); } }) $(document).mousedown(function(e){})
$(document) It is to get the entire web page document object, similar to the native window.ducument
mousedown is a mouse event, which means when the mouse pointer moves over the element and the mouse button is pressed, similar events include:
mouseup: when on the element When the mouse button is released
mouseover: When the mouse pointer is over the element
$(e.target)
$(e.target) represents the element that gets the click event.
parent()
$(e.target).parent("#info").length is to get the parent element of the current click event element with the id of info.