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

Two ways to hide the div by clicking elsewhere on the page_javascript skills

WBOY
Release: 2016-05-16 17:14:24
Original
973 people have browsed it
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.
Copy code The code is as follows:



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.
Copy code The code is as follows:



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.
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!