Task requirements:
1. Registration event (binding event)
1.1 overview of registration events
Adding an event to an element is called a registration event or a binding event. There are two ways to register events: traditional method and event listening registration method.
1.1.1 traditional registration method
- Use the event onclick starting with on
- <button onclick="alert('hi~')"></button>
- btn.onclick = function() {};
- Features: uniqueness of registration events
- Only one handler can be set for the same element and event. The last registered handler will overwrite the previously registered handler.
1.1.2 event listening registration method
- w3c standard recommendation
- addEventListener(), which is a method
- Ie before IE9 does not support this method. attachEvent() can be used instead
- Features: multiple listeners can be registered for the same element and event
- Execute in order of registration
<body> <button>123</button> <button>456</button> <script> var btns = document.querySelectorAll('button'); // Traditional event registration btns[0].onclick = function () { alert('999'); } btns[0].onclick = function () { alert('000'); } // Event listening registration method addEventListener // (1) The event type inside is a string, which must be quoted without on // (2) Multiple listeners (event handlers) can be added to the same element and the same event btns[1].addEventListener('click', function () { alert(11); }) btns[1].addEventListener('click', function () { alert(22); }) </script> </body>
1.2 addEventListener # event listening method
eventTarget.addEventListener(type, listener[, useCapture])
eventTarget. The addeventlistener () method registers the specified listener with the EventTarget (target object). When the object triggers the specified event, the event handling function will be executed.
The method receives three parameters:
- Type: event type string, such as click and mouseover. Note that there is no on here.
- listener: event handling function, which will be called when an event occurs
- useCapture: optional parameter. It is a Boolean value. The default value is false. After learning the DOM event flow, we will learn further.
Warning: ≥ IE9 version support
1.3 attachEvent event listening method (understand)
eventTarget.attachEvent(eventNameWithOn, callback)
eventTarget. The attachevent () method registers the specified listener with the EventTarget (target object). When the object triggers the specified event, the specified callback function will be executed. The method receives two parameters:
- eventNameWithOn: event type string, such as onclick and onmouseover, with on
- Callback: event handling function. When the target triggers an event, the callback function is called
Warning: unique to IE8 and earlier versions, it doesn't work in chrome. To be compatible, you can customize new functions.
2. Delete event (unbind event)
2.1 deleting events by traditional method
eventTarget.onclick = null;
2.2 delete event by event listening method
2.2.1 removeEventListener (>=IE9)
eventTarget.removeEventListener(type, listener[, useCapture]);
Tip: an object may be bound with many events. For the removeEventListener method, you need to specify the event listener to be deleted. Therefore, when registering events, you need to encapsulate the event function in a variable in advance. Then pass the variable to the removeEventListener method.
<style> div { width: 50px; height: 50px; background-color: pink; } </style> </head> <body> <div>1</div> <div>2</div> <div>3</div> <script> var divs = document.querySelectorAll('div'); divs[0].onclick = function () { alert(22); //There is no need to refresh. Each click will pop up // 1. Delete events in traditional way divs[0].onclick = null; //After unbinding, click to pop up only once } // 2. removeEventListener delete event divs[1].addEventListener('click', fn) //The function inside does not need to call parentheses function fn() { alert(99); divs[1].removeEventListener('click', fn); } </script> </body>
3. DOM event flow
3.1 definitions
Event flow describes the order in which events are received from the page.
When an event occurs, it will propagate between element nodes in a specific order. This propagation process is DOM event flow.
For example, we registered a click event for a div.
DOM event flow is divided into three stages:
Capture phase => Current target stage => bubbling phase
-
Event bubbling: IE first proposed that the event is received by the most specific element at the beginning, and then propagated up to the top node of DOM level by level.
-
Event capture: Netscape was first proposed. It starts from the top node of DOM, and then propagates down to the most specific element.
When we throw a stone into the water, first of all, it will have a descent process, which can be understood as the capture process from the top to the most specific element (target point) of the event; Then bubbles will be generated, which will float to the water after the lowest point (the most specific element). This process is equivalent to event bubble.
3.2 notes
- Only one stage of capture or bubbling can be executed in JS code.
- onclick and attachEvent can only get the bubbling phase.
- addEventListener(type, listener[, useCapture]) if the third parameter is true, it means to call the event handler in the event capture phase; If it is false (the default is false if it is not written), it means that the event handler is called in the event bubbling stage.
- In actual development, we rarely use event capture, and we pay more attention to event bubbling.
- Some events do not bubble, such as onblur, onfocus, onmousenter, onmousesave
- Event bubbling sometimes brings trouble, and sometimes helps to do some events skillfully. We'll explain later.
<style> .father { width: 300px; height: 300px; background-color: pink; } .son { width: 100px; height: 100px; background-color: purple; } </style> </head> <body> <div class="father"> <div class="son">son Box</div> </div> <script> // 1. Only one stage of capture or bubbling can be executed in JS code. // 2.onclick and attachEvent can only get the bubbling stage. // 3. In the capture phase, if the third parameter of addEventListener is true, it means that it is in the event capture phase // document -> html -> body -> father -> son // var son = document.querySelector('.son'); // son.addEventListener('click', function () { // alert('son'); // }, true) // var father = document.querySelector('.father'); // father.addEventListener('click', function () { // alert('father'); // }, true) // 3. In the bubbling phase, if the third parameter of addEventListener is false, it means that it is in the event bubbling phase // son -> father -> body -> html ->document var son = document.querySelector('.son'); son.addEventListener('click', function () { alert('son'); }, false) var father = document.querySelector('.father'); father.addEventListener('click', function () { alert('father'); }, false) </script> </body>
4. Event object
4.1 what is the event object
eventTarget.onclick = function(event) {} eventTarget.addEventListener('click', function(event) {}) // This event is the event object. We also like to write it as e or evt
- Official explanation: the event object represents the state of the event, such as the state of the keyboard keys, the position of the mouse, and the state of the mouse buttons.
- Simple understanding: after an event occurs, the collection of a series of information data related to the event is put into this object. This object is the event object event, which has many properties and methods.
For example:
- Who bound this event.
- If the mouse triggers an event, you will get the relevant information of the mouse, such as the mouse position.
- If the keyboard triggers an event, you will get the relevant information of the keyboard, such as which key you pressed.
4.2 usage syntax of event object
eventTarget.onclick = function(event) { // This event is the event object. We also like to write it as e or evt } eventTarget.addEventListener('click', function(event) { // This event is the event object. We also like to write it as e or evt })
This event is a formal parameter. The system helps us set it as an event object without passing an argument.
When we register an event, the event object will be automatically created by the system and passed to the event listener (event handler) in turn.
4.3 compatibility scheme of event object
There is a compatibility problem with the acquisition of the event object itself:
- In the standard browser, the parameters passed by the browser to the method can be obtained by defining the formal parameter e.
- In IE6~8, the browser will not pass parameters to the method. If necessary, it needs to go to window Get the lookup in event.
resolvent:
e = e || window.event;
<body> <div>123</div> <script> // Event object var div = document.querySelector('div'); div.onclick = function (e) { // console.log(e); // console.log(window.event); // e = e || window.event; console.log(e); } // div.addEventListener('click', function (e) { // console.log(e); // }) // 1. event is an event object, which is written into the parentheses of the listening function and used as a formal parameter // 2. The event object will exist only when there is an event. It is created by the system and does not need us to pass parameters // 3. The event object is a collection of a series of related data of our data, which is related to the data // For example, the mouse click contains the relevant information of the mouse (mouse coordinates), and the keyboard event contains the relevant information of the keyboard event (judge which key the user presses) // 4. We can name this event object directly, such as event, evt, e // 5. The event object also has compatibility problems ie678 through window Event compatibility e = e | window event </script> </body>
4.4 common attributes and methods of event objects
Event object attribute method | explain |
---|---|
e.target | Returns the object that triggered the event (standard) |
e.srcElement | Returns the object that triggered the event (non-standard) |
e.type | Return event type |
e.preventDefault() | Block default events (standard) |
e.returnValue = true | Block default events (non standard, IE678) |
e.stopPropagation() | Prevent foaming (standard) |
e.cancelBubble | Prevent foaming (non-standard, IE678) |
Warning: non standard (IE678) solutions only need to be understood.
4.4.1 comparison of event object attribute e.target and this
<body> <div>123</div> <ul> <li>aaa</li> <li>aaa</li> <li>aaa</li> </ul> <script> // 1. e.target returns the object (element) that triggers the event. this returns the object that binds the event // Difference: if e.target clicks the element, it will return the element. If this element is bound to the click event, then who will be returned var div = document.querySelector('div'); div.addEventListener('click', function (e) { console.log(e.target); console.log(this); }) var ul = document.querySelector('ul'); ul.addEventListener('click', function (e) { // If we bind an event to ul, this points to ul console.log(this); //Click ul to display UL console.log(e.currentTarget); // e.target points to the object we clicked on (we clicked on li) console.log(e.target); //Appear li }) // Understanding compatibility // div.onclick = function () { // e = e || window.event; // var target = e.target || e.srcElement; // console.log(target); // } </script> </body>
4.4.2 block event default behavior
<body> <div>123</div> <a href="http://www.baidu. Com "> Baidu</a> <form action="http://www.baidu.com"> <input type="submit" value="Submit" name="sub"> </form> <script> // 1. Return event type var div = document.querySelector('div'); div.addEventListener('click', fn); div.addEventListener('mouseover', fn); function fn(e) { console.log(e.type); } // 2. Block the default behavior (event) so that the link does not jump or the submit button does not submit var a = document.querySelector('a'); a.addEventListener('click', function (e) { e.preventDefault(); //DOM standard writing }) // 3. Traditional registration methods a.onclick = function () { // Ordinary browser e.preventDefault(); method // e.preventDefault(); // Lower version browser ie678 returnValue; attribute // e.returnValue; // We can also use return false to prevent the default behavior. There is no compatibility problem // The feature is that the code behind return is not executed and is limited to the traditional registration method return false; } </script> </body>
5. Prevent event bubbling
5.1 two ways to prevent event bubbling
Event bubbling: it is received by the most specific element at the beginning, and then propagated up to the top node of DOM level by level. The characteristics of event bubbling will bring both disadvantages and benefits, which we need to master flexibly.
Prevent event bubbling:
- Standard writing method: use the stopPropagation() method in the event object.
e.stopPropagation();
- Nonstandard writing: IE 6-8 uses the cancelBubble attribute of the event object
e.cancelBubble = true;
Tip: set the stopPropagation() method of the event for the corresponding child element node, which is equivalent to blocking the event bubbling at this node. The event cannot continue to be delivered to the parent node.
<style> .father { width: 300px; height: 300px; background-color: pink; } .son { width: 100px; height: 100px; background-color: purple; } </style> </head> <body> <div class="father"> <div class="son">son</div> </div> <script> // Stop bubbling dom recommended standard stopPropagation() var son = document.querySelector('.son'); son.addEventListener('click', function (e) { alert('son'); e.stopPropagation(); // Stop stop Propagation. If you stop bubbling, father and document will no longer pop up }, false) var father = document.querySelector('.father'); father.addEventListener('click', function (e) { alert('father'); e.stopPropagation(); }, false) document.addEventListener('click', function () { alert('document'); }) </script> </body>
5.2 compatibility solution to prevent event bubbling
if(e && e.stopPropagation) { e.stopPropagation(); } else { window.event.cancelBubble = true; }
6. Event entrustment (agency and delegation)
6.1 Preface
The characteristics of event bubbling will bring both disadvantages and benefits, which we need to master flexibly. There are the following scenes in life:
- There are 100 students in our class and 100 couriers. It takes a long time to send them one by one. At the same time, each student also needs to queue up to receive it, which also takes a long time. What about it?
- Solution: the couriers entrust 100 couriers to the head teacher. The head teacher puts these couriers in the office and the students can get them by themselves after class.
- Advantages: it's easy for the courier to entrust to the head teacher. It is also convenient for students to get it, because they believe in the head teacher.
The characteristics of event bubbling will bring both disadvantages and benefits, which we need to master flexibly. There are also such scenes in the program:
<body> <ul> <li>You know, you should have a bullet box in hand</li> <li>You know, you should have a bullet box in hand</li> <li>You know, you should have a bullet box in hand</li> <li>You know, you should have a bullet box in hand</li> <li>You know, you should have a bullet box in hand</li> </ul> <script> // Principle: recommend listeners to the parent node and use event bubbling to affect each child node var ul = document.querySelector('ul'); ul.addEventListener('click', function (e) { // alert('know it or not, there should be a bullet box in hand '); // e.target can get the object we click e.target.style.backgroundColor = 'pink'; }) </script> </body>
Clicking each li will pop up a dialog box. It used to be very hard to register events for each li, and the more times you access the DOM, the longer the interaction readiness time of the whole page.
6.2 principle of event entrustment
-
Event delegation: also known as event proxy, which is called event delegation in jQuery.
-
Principle: instead of setting the event listener separately for each child node, the event listener is set on its parent node, and then the bubble principle is used to affect the setting of each child node.
The above case: register the click event for ul, and then use the target of the event object to find the currently clicked li. Because clicking li, the event will bubble on ul. If ul has a registered event, the event listener will be triggered. -
Function: we only operate DOM once, which improves the performance of the program.
7. Common mouse events
7.1 common mouse events
-
Disable right mouse button menus
contextmenu mainly controls when the context menu should be displayed. It is mainly used by programmers to cancel the default context menu.document.addEventListener('contextmenu', function(e) { e.preventDefault(); })
-
Disable mouse selection (select Start starts selection)
document.addEventListener('selectstart', function(e) { e.preventDefault(); })
Case:
<body> I'm a difficult text. I can select it for you, but I won't right-click to copy it. Even the selection is not allowed. It's so overbearing! Hee hee <script> // 1. contextmenu disable context menu document.addEventListener('contextmenu', function (e) { e.preventDefault(); }) // 2. selectstart prohibits the selection of text document.addEventListener('selectstart', function (e) { e.preventDefault(); }) </script> </body>
7.2 mouse event object
Event object represents the state of the event and a collection of a series of information related to the event. At this stage, we mainly use mouse event object MouseEvent and keyboard event object KeyboardEvent.
Mouse event object | explain |
---|---|
e.clientX | Returns the X coordinate of the mouse relative to the viewable area of the browser window |
e.clientY | Returns the Y coordinate of the mouse relative to the viewable area of the browser window |
e.pageX | Return the X coordinate of the mouse relative to the document page IE9 + support |
e.pageY | Return the Y coordinate of the mouse relative to the document page IE9 + support |
e.screenX | Returns the X coordinate of the mouse relative to the computer screen |
e.screenY | Returns the Y coordinate of the mouse relative to the computer screen |
<style> body { height: 3000px; } </style> </body> </head> <body> <script> // Mouse object MouseEvent document.addEventListener('click', function (e) { // 1. The client returns the x-axis and y-axis coordinates in the visual area console.log(e.clientX); console.log(e.clientY); // 2. page returns the x-axis and y-axis coordinates of the document on the page console.log(e.pageX); console.log(e.pageY); // 1. screen returns the x-axis and y-axis coordinates on the computer screen console.log(e.screenX); console.log(e.screenY); }) </script> </body>
Must master case: pattern follows mouse move
<style> img { position: absolute; } </style> </head> <body> <img src="image/angel.gif" alt=""> <script> var pic = document.querySelector('img'); document.addEventListener('mousemove', function (e) { // 1. mousemove this event will be triggered as long as the mouse moves to 1px // console.log(1); // 2. Core principle: each time you move the mouse, you will get the latest coordinates. Take the x and y coordinates as the top and left of the picture var x = e.pageX; var y = e.pageY; console.log('x The coordinates are' + x, 'y The coordinates are' + y); // 3. Don't forget to add px units pic.style.left = x - 50 + 'px'; pic.style.top = y - 40 + 'px'; }) </script> </body>
8. Common keyboard events
8.1 common keyboard events
Events can be triggered not only with the mouse, but also with the keyboard.
Keyboard events | Trigger event |
---|---|
onkeyup | Triggered when a keyboard key is released |
onkeydown | Triggered when a keyboard key is pressed |
onkeypress | Triggered when a keyboard key is pressed, but the function key (ctrl, shif, arrow, etc.) is not recognized |
Warning: onkeypress is obsolete. Although there is still browser support, it may stop supporting in the future. Use keydown instead.
<body> <script> // 1. keyup is triggered when a keyboard key pops up // document.onkeyup = function () { // console.log('I bounced '); // } document.addEventListener('keyup', function () { console.log('I bounced up'); }) // 2. onkeydown is triggered when a keyboard key is pressed document.addEventListener('keydown', function () { console.log('I pressed'); }) </script> </body>
The execution sequence of the three events is: keydown---keypress---keyup
8.2 keyboard event object
Keyboard event object properties | explain |
---|---|
key | Returns the name value of the physical key (recommended) |
keyCode | Returns the ASCII value of the key |
Warning: keyCode is obsolete: this feature has been removed from the Web standard. Although some browsers still support it, it may stop supporting it at some time in the future. Please try not to use this feature. It must be used. Please use key instead—— MDN
<body> <script> // The keyCode attribute can get the ASCII code value of the corresponding key document.addEventListener('keyup', function (e) { // console.log(e); console.log('up :' + e.keyCode); //Press a to get 65 press a to get 65 // 1. keyup and keydown events are not case sensitive. Both a and a get 65 // The user can use the ASCII key to determine which value is returned if (e.keyCode === 65) { alert('You pressed a key'); } else { alert('You didn't press a key'); } }) document.addEventListener('keydown', function (e) { // console.log(e); console.log('down :' + e.keyCode); //Press a to get 65 press a to get 65 // 1. keyup and keydown events are not case sensitive. Both a and a get 65 }) document.addEventListener('keypress', function (e) { // console.log(e); console.log('press :' + e.keyCode); //Press a to get 97 press a to get 65 // 2. keypress events are case sensitive. A is 97 and a is 65 }) </script> </body>