day03 event advanced

1. Registration event (binding event)

① Overview

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 method listening registration method

Traditional registration method:

Use the event onclick starting with on
<button οnclick="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

Method 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

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

③ attachEvent event listening method

 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
Note: IE8 and earlier versions support

④ Register event compatibility solutions

 function addEventListener(element, eventName, fn) {
/ / judge whether the current browser supports the addEventListener method
      if (element.addEventListener) {
        element.addEventListener(eventName, fn); / / the third parameter is false by default
      } else if (element.attachEvent) {
        element.attachEvent('on' + eventName, fn);
      } else {
/ / equivalent to element onclick = fn;
        element['on' + eventName] = fn;
 }

Principle of compatibility processing: first take care of most browsers, and then deal with special browsers


2. Delete event (unbind event)

① How to delete an event

1. Traditional registration method

eventTarget.onclick = null;

2. Method monitoring registration method

eventTarget.removeEventListener(type, listener[, useCapture]);
eventTarget.detachEvent(eventNameWithOn, callback);

② Remove event compatibility solution

 function removeEventListener(element, eventName, fn) {
/ / judge whether the current browser supports the removeEventListener method
      if (element.removeEventListener) {
        element.removeEventListener(eventName, fn); / / the third parameter is false by default
      } else if (element.detachEvent) {
        element.detachEvent('on' + eventName, fn);
      } else {
        element['on' + eventName] = null;
 }

3.DOM event flow

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, a div is registered with a click event:

DOM event flow is divided into three stages:
1. Capture phase
2. Current target stage
3. Bubbling stage

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 and float to the water after the lowest point (the most specific element). This process is equivalent to event bubble.

When an event occurs, it will propagate between element nodes in a specific order. This propagation process is DOM event flow.

be careful:
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. If the third parameter of addeventlistener (type, listener [, usecapture]) 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.
4. In actual development, we seldom use event capture, and we pay more attention to event bubbling.
5. Some events are not bubbling, such as onblur, onfocus, onmousenter, onmouselive
6. Event bubbling sometimes brings trouble, and sometimes helps to do some events skillfully, which we will explain later.


4. 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:
1. Who bound this event.
2. If the mouse triggers an event, you will get the relevant information of the mouse, such as the mouse position.
3. If the keyboard triggers an event, you will get the relevant information of the keyboard, such as which key you pressed.

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

③ Compatibility scheme of event object

There is a compatibility problem with the acquisition of the event object itself:
1. In the standard browser, the parameters passed by the browser to the method can be obtained by defining the formal parameter e.
2. In IE6~8, the browser will not pass parameters to the method. If necessary, you need to go to window Get the lookup in event.
solve:
e = e || window.event;

④ Common properties and methods of event objects

e. Difference between target and this:
This is the element bound by the event, and the caller of this function (the element bound by the event)
e.target is the element triggered by the event.

 


5. Prevent event bubbling

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

Standard writing method: use the stopPropagation() method in the event object

 e.stopPropagation()

Non standard writing: IE 6-8 # uses the cancelBubble attribute of the event object

 e.cancelBubble = true;

② Compatibility solution to prevent event bubbling

  if(e && e.stopPropagation){
      e.stopPropagation();
  }else{
      window.event.cancelBubble = true;
  }


6. Event entrustment (agency and delegation)

Event delegation: event delegation is also called event proxy, which is called event delegation in jQuery.


Principle of event delegation: 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.

   <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: 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>


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 of event delegation: DOM is operated only once, which improves the performance of the program.

 


7. Common mouse events

1. Disable right-click menu
Context menu: it 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();
})

2. Disable mouse selection (select Start starts selection)

   document.addEventListener('selectstart', function(e) {
    e.preventDefault();
   })

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

    <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.clientX);
            console.log(e.clientY);
            console.log('---------------------');

            // 2. The page mouse is used most in 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>

Case: Angel following mouse

<!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>
        img {
            position: absolute;
            top: 2px;
        }
    </style>
</head>

<body>
    <img src="images/angel.gif" alt="">
    <script>
        var pic = document.querySelector('img');
        document.addEventListener('mousemove', function(e) {
            // 1. mousemove this event will be triggered as long as we move 1px the mouse
            // console.log(1);
            // 2. Core principle: every time the mouse moves, we will get the latest mouse coordinates. Take the x and y coordinates as the top and left values of the picture to move 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 to left and top
            pic.style.left = x - 50 + 'px';
            pic.style.top = y - 40 + 'px';


        });
    </script>
</body>

</html>

 


8. Common keyboard events

be careful:
1. If you use addEventListener, you do not need to add on
2. The difference between onkeypress and the previous two is that it does not recognize function keys, such as left and right arrows, shift, etc.
3. The execution sequence of the three events is: keydown -- keypress -- keyup

② Keyboard event object

Note: onkeydown and onkeyup # are not case sensitive, and onkeypress is case sensitive.
In our actual development, we use keydown and keyup more, which can recognize all keys (including function keys)
Keypress does not recognize function keys, but the keyCode attribute is case sensitive and returns different ASCII values

Case: simulate Jingdong 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>

Case: simulate JD express order No. query

<!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>
        * {
            margin: 0;
            padding: 0;
        }
        
        .search {
            position: relative;
            width: 178px;
            margin: 100px;
        }
        
        .con {
            display: none;
            position: absolute;
            top: -40px;
            width: 171px;
            border: 1px solid rgba(0, 0, 0, .2);
            box-shadow: 0 2px 4px rgba(0, 0, 0, .2);
            padding: 5px 0;
            font-size: 18px;
            line-height: 20px;
            color: #333;
        }
        
        .con::before {
            content: '';
            width: 0;
            height: 0;
            position: absolute;
            top: 28px;
            left: 18px;
            border: 8px solid #000;
            border-style: solid dashed dashed;
            border-color: #fff transparent transparent;
        }
    </style>
</head>

<body>
    <div class="search">
        <div class="con">123</div>
        <input type="text" placeholder="Please enter your courier number" class="jd">
    </div>
    <script>
        // When you enter the content of the express order number, the large font box (con) above will display (the font size inside is larger)
        // Form detection user input: add keyboard events to the form
        // At the same time, get the value in the express order number and assign it to the con box (innerText) as the content
        // If the content in the express order number is empty, the large font box (con) box will be hidden
        var con = document.querySelector('.con');
        var jd_input = document.querySelector('.jd');
        jd_input.addEventListener('keyup', function() {
                // console.log('input content ');
                if (this.value == '') {
                    con.style.display = 'none';
                } else {
                    con.style.display = 'block';
                    con.innerText = this.value;
                }
            })
            // When we lose focus, we hide the con box
        jd_input.addEventListener('blur', function() {
                con.style.display = 'none';
            })
            // When we get the focus, the con box is displayed
        jd_input.addEventListener('focus', function() {
            if (this.value !== '') {
                con.style.display = 'block';
            }
        })
    </script>
</body>

 

Keywords: Javascript Front-end

Added by NogDog on Tue, 15 Feb 2022 11:14:08 +0200