Idea 1 The first idea is divided into two steps
The first step: Bind an event handler to the click event of the document to hide the div
Step 2: Bind an event handler to the click event of the div to prevent the event from bubbling to the document, and calling the onclick method of the document hides the div.
This way When a non-div area of the page is clicked, the onclick method of the document will be called directly or layer by layer to hide the div. When a div or its sub-elements are clicked, the event will always bubble up to the div itself, which will prevent the event. Continuing to bubble, the onclick method of the document will not be called, causing the div to be hidden, thus fulfilling our needs.
Idea 2 We mentioned before that when an event on the DOM is triggered, an event object event will be generated. This object contains everything related to the event. Information, including the element that generated the event, event type and other related information. The parameter passed in by the click event handler of the div in the first idea is this event object. There are several different ways to access the event object in IE, depending on how you specify the event handler. When adding event handlers directly to DOM elements, the event object exists as a property of the window object.
The event object contains an important attribute: target(W3C)/srcElement(IE). This attribute identifies the original element that triggered the event. The second idea is to use this attribute. We can directly bind an event handler to the click event of the document, and determine in the event handler whether the event source is the div element with id==test or its sub-element. If so, the method return does not perform any operation. If not, the event is hidden. div.
In this way, when you click anywhere on the page, the click event will bubble up to the document, and the event handler will determine the event Whether the source is a div with id==test or its sub-element, if it is a method return, otherwise hiding the div can also achieve our needs.