DOM events advanced
- Registration event
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button>Traditional registration event</button> <button>Method listens for registration events</button> <button>ie9 attachEvent</button> <script> var btns = document.querySelectorAll('button'); // 1. Traditional registration events btns[0].onclick = function() { alert('hi'); } btns[0].onclick = function() { alert('hao a u'); } // 2. Event listener registers the event addEventListener // (1) The event type inside is a string. It 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(22); }) btns[1].addEventListener('click', function() { alert(33); }) // 3. attachEvent ie9 previous versions support btns[2].attachEvent('onclick', function() { alert(11); }) </script> </body> </html>
- Delete event
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 100px; height: 100px; 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(11); // 1. Delete events in traditional way divs[0].onclick = null; } // 2. removeEventListener delete event divs[1].addEventListener('click', fn) // fn inside does not need to be called with parentheses function fn() { alert(22); divs[1].removeEventListener('click', fn); } // 3. detachEvent divs[2].attachEvent('onclick', fn1); function fn1() { alert(33); divs[2].detachEvent('onclick', fn1); } </script> </body> </html>
- Event flow of dom
Event flow: the process of event propagation is called event flow, which describes the order in which events are received from the page
DOM event flow is divided into three stages: capture stage (from large to small), current target stage, bubbling stage (from small to large)
Event bubbling: ie first proposed that there is a process in which the most specific elements propagate level by level up to the top node of DOM
Event capture: it starts from the top node of DOM and propagates down level by level to the most specific element receiving process
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .father { overflow: hidden; width: 300px; height: 300px; margin: 100px auto; background-color: pink; text-align: center; } .son { width: 200px; height: 200px; margin: 50px; background-color: purple; line-height: 200px; color: #fff; } </style> </head> <body> <div class="father"> <div class="son">son Box</div> </div> <script> // dom event flow has three stages // 1. Only one stage of capture or bubbling can be executed in JS code. // 2. onclick and attachEvent (ie) can only get the bubbling stage. // 3. In the capture phase, if the third parameter of addEventListener is true, it is in the 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); // 4. In the bubbling stage, if the third parameter of addEventListener is false or omitted, it is in the bubbling stage son - > father - > body - > HTML - > document var son = document.querySelector('.son'); son.addEventListener('click', function() { alert('son'); }, true); var father = document.querySelector('.father'); father.addEventListener('click', function() { alert('father'); }, true); document.addEventListener('click', function() { alert('document'); }) </script> </body> </html>
- Event object
The event object is a collection of a series of relevant data of our events. For example, the mouse click contains the relevant information of the mouse, and the mouse coordinates. If it is a keyboard event, it contains the information of the keyboard event, such as judging that the user pressed the key
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 100px; height: 100px; background-color: pink; } </style> </head> <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 written into the parentheses of our listening function as a formal parameter // 2. The event object will exist only when there is an event. It is automatically created by the system and does not need us to pass parameters // 3. The event object is the collection of a series of relevant data of our events. For example, the mouse click contains the relevant information of the mouse, and the mouse coordinates. If it is a keyboard event, it contains the information of the keyboard event, such as judging that the user pressed the key // 4. The event object can be named by ourselves, such as event, evt and e // 5. The event object also has compatibility problems ie678 through window The writing method of event compatibility e = e | window event; </script> </body> </html>
Common event objects:
(1)e.target
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { width: 100px; height: 100px; background-color: pink; } </style> </head> <body> <div>123</div> <ul> <li>abc</li> <li>abc</li> <li>abc</li> </ul> <script> // Properties and methods of common event objects // The event returned by the bound element (1. E) is the event returned by the bound object (1. E) // 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); console.log(e.currentTarget); // e.target points to the object we clicked. Who triggered this event? We clicked li e.target points to li console.log(e.target); }) // Understanding compatibility // div.onclick = function(e) { // e = e || window.event; // var target = e.target || e.srcElement; // console.log(target); // } // 2. Understand that there is a very similar attribute to this. Currenttarget ie678 doesn't know </script> </body> </html>
(2) Block the default behavior (event) so that the link does not jump or the submit button does not submit
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> </style> </head> <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> // Properties and methods of common event objects // 1. Return event type var div = document.querySelector('div'); div.addEventListener('click', fn); div.addEventListener('mouseover', fn); div.addEventListener('mouseout', 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(e) { // Ordinary browser e.preventDefault(); method // e.preventDefault(); // Lower browser ie678 returnValue property // e.returnValue; // We can also use return false to prevent the default behavior. There is no compatibility problem: the code behind return is not executed, and it is only limited to the traditional registration method return false; alert(11); } </script> </body> </html>
- Prevent event bubbling
Two methods: stopPropagation() or e.cancelBubble = true// Non standard cancel bubble
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .father { overflow: hidden; width: 300px; height: 300px; margin: 100px auto; background-color: pink; text-align: center; } .son { width: 200px; height: 200px; margin: 50px; background-color: purple; line-height: 200px; color: #fff; } </style> </head> <body> <div class="father"> <div class="son">son Son</div> </div> <script> // Properties and methods of common event objects // Stop bubbling dom recommended standard stopPropagation() var son = document.querySelector('.son'); son.addEventListener('click', function(e) { alert('son'); e.stopPropagation(); // Stop stop Propagation e.cancelBubble = true; // Non standard cancel bubble }, false); var father = document.querySelector('.father'); father.addEventListener('click', function() { alert('father'); }, false); document.addEventListener('click', function() { alert('document'); }) </script> </body> </html>
- Event delegation
The core principle of event delegation: do not set click events for each word node separately, and bind the events to the common ancestor elements uniformly. In this way, when the event of the descendant element is triggered, it will bubble to the ancestor element all the time, so as to process the events through the response function of the ancestor. For example, add a listener to the parent node and use event bubble to affect each child node
The function of event delegation: dom is operated only once, which improves the performance of the program
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <ul> <li>Do you know, I should have a bullet box in hand!</li> <li>Do you know, I should have a bullet box in hand!</li> <li>Do you know, I should have a bullet box in hand!</li> <li>Do you know, I should have a bullet box in hand!</li> <li>Do you know, I should have a bullet box in hand!</li> </ul> <script> // The core principle of event delegation: do not set the click time for each word node separately, add a listener to the parent node, and use event bubbling to affect each child node var ul = document.querySelector('ul'); ul.addEventListener('click', function(e) { // alert('whether you know it or not, click I should have a bullet frame in hand! '); // e.target is the object we can click on e.target.style.backgroundColor = 'pink'; }) </script> </body> </html>
- Common mouse events
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> I am a text that I don't want to share <script> // 1. contextmenu we can disable the right-click menu document.addEventListener('contextmenu', function(e) { e.preventDefault(); }) // 2. The text selectstart cannot be selected document.addEventListener('selectstart', function(e) { e.preventDefault(); }) </script> </body> </html>
Mouse event object:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> body { height: 3000px; } </style> </head> <body> <script> // Mouse event object MouseEvent document.addEventListener('click', function(e) { // 1. x and y coordinates of the client mouse in the visible area console.log(e); console.log(e.clientX); console.log(e.clientY); console.log('---------------------'); // 2. The page mouse is on the x and y coordinates of the page document console.log(e.pageX); console.log(e.pageY); console.log('---------------------'); // 3. screen the x and y coordinates of the mouse on the computer screen console.log(e.screenX); console.log(e.screenY); }) </script> </body> </html>
Case: mouse movement
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <img src="./image/angel.gif" alt=""> </body> <style> img { position: absolute; top: 2px; } </style> <script> var img=document.querySelector("img") document.addEventListener("mousemove",function(e){ var x=e.pageX var Y=e.pageY img.style.left=x-40+'px' img.style.top=Y-50+'px' }) </script> </html>
- Common keyboard events
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> // Common keyboard events //1. Triggered when the Keyup button pops up // document.onkeyup = function() { // console.log('I bounced '); // } document.addEventListener('keyup', function() { console.log('I bounced up'); }) //3. When the keypress key is pressed, the unrecognized function key is triggered, such as the left and right arrows of ctrl shift document.addEventListener('keypress', function() { console.log('I pressed press'); }) //2. When the Keydown key is pressed, it will trigger a function key that can be recognized, such as the left and right arrows of ctrl shift document.addEventListener('keydown', function() { console.log('I pressed down'); }) // 4. Execution sequence of three events keydown -- keypress -- keyup // Why use keyup event operation instead of keypress or keydown? // Because of the characteristics of keypress or keydown in the text box, when an event occurs, the text still falls into the text box, the keyup event is triggered, and the text also falls into the text box </script> </body> </html>
The ASCII code value of the corresponding key can be obtained from the keyCode attribute in the keyboard event object
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> // The ASCII code value of the corresponding key can be obtained from the keyCode attribute in the keyboard event object // 1. Our keyup and keydown events are not case sensitive. Both A and A get 65 // 2. Our keypress event is case sensitive. A 97 and a get 65 document.addEventListener('keyup', function(e) { console.log(e); console.log('up:' + e.keyCode); // We can use the ASCII code value returned by keycode to judge which key the user pressed if (e.keyCode === 65) { alert('You pressed a key'); } else { alert('You didn't press a key') } }) document.addEventListener('keypress', function(e) { // console.log(e); console.log('press:' + e.keyCode); }) </script> </body> </html>
Imitate Jingdong case key input content
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input type="text"> <script> // Core idea: check whether the user has pressed the s key. If the user presses the s key, the cursor will be positioned in the search box // Use the keyCode in the keyboard event object to judge whether the user pressed the s key // Search box to get focus: use the focus() method in js var search = document.querySelector('input'); document.addEventListener('keyup', function(e) { // console.log(e.keyCode); if (e.keyCode === 83) { search.focus(); } }) </script> </body> </html>