Dom - Advanced events

Posted by mrodrigues on Sat, 29 Jan 2022 04:10:38 +0100

Advanced events

1, Registration event (binding event)

  1. Traditional registration events are unique. Only one function can be set, and the later registered function will overwrite the new function
  2. Method listening registration method: addEventListener(type,listener[,useCapture])
    (1) The event type inside is a string, which must be quoted without on
    (2) Multiple listeners can be added to the same element and event
    ① Type: event type string, such as click and mouseover. Note that it does not take on
    ② 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.

2, Delete event (unbind event)

1. Add div.onclick = null inside the function for traditional deletion events
2. Register event deletion: the removeEventListener(type, function) function does not need to add parentheses

<div>1</div>
<script>
    var div1 = document.querySelector('div');
    div1.addEventListener = ('click', fn)

    function fn() {
        alert('hi~');
        div1.removeEventListener('click', fn);
    }
</script>

3, DOM event flow -- event propagation process

  1. Capture phase
  2. Current target stage
  3. bubbling phase

※ attention
① js code can only execute one of the capture or bubble phases
② onclick and attachEvent can only get the bubbling phase
③ If the third parameter of addEventListener is true, it means to call the event handler in the event capture phase; If false, it means that the event handler is called during the event bubbling phase
④ Event capture is rarely used in actual development, and event bubbling is more concerned
⑤ There is no bubble in some time, such as onblur, ommouseover, ommouseleave

4, Event object

div.onclick = function(event){}
(1) Concept: event means that the event object is written into the parentheses of the listening function when the form is referenced
(2) Usage:

  1. The event object exists only when there is an event. It is automatically created by the system. We don't need to pass parameters to the event listener in turn
  2. The event object is the collection of a series of related data of our event, and the information related to the event
  3. This event object can be named by ourselves, such as event, evt, e, etc

(3) Common properties and methods

  1. e.target: returns the element that triggers the event, and this returns the element that binds the event.
  2. e.type: returns the event type, such as click, mouseover, without on
  3. e.preventDefault(): prevents default events, such as not allowing links to jump
<a href="https://www.baidu. COM / "> Baidu</a>
<script>
    var aa = document.querySelector('a');
    aa.addEventListener('click', function(e) {
        e.preventDefault();
    })
</script>
  1. e.stopPropagation(): stop bubbling
<div>me</div>
<script>
    var me = document.querySelector('div');
    me.addEventListener('click', function(e) {
        alert('I played it out');
        e.stopPropagation();
    });
    document.addEventListener('click', function(e) {
        alert('I played it out, too');
    });
</script>

5, Event delegation

  1. 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
<ul>
    <li>I have a pop-up window</li>
    <li>I have a pop-up window</li>
    <li>I have a pop-up window</li>
    <li>I have a pop-up window</li>
    <li>I have a pop-up window</li>
</ul>
<script>
    var ul = document.querySelector('ul');
    ul.addEventListener('click', function(e) {
        alert('I played it out');
        // e.target can get the clicked object, so it can be used to set a separate style
        e.target.style.backgroundColor = 'red';
        // If you want to achieve a change in color, you can review the idea of exclusivity
    })
</script>

6, Common mouse events

(1)

  1. contextmenu: disable context menu
  2. selectstart: disable mouse selection
  3. mousemove: mouse movement event

(2) Mouse event object MouseEvent

  1. clientX, clientY: coordinates relative to the viewable area of the browser window
  2. pageX, pageY: coordinates relative to the edge of the document
  3. screenX, screenY: the coordinates of the mouse on the computer screen

7, Common keyboard events

(1) Three event execution sequences: Keydown keypress Keyup

  1. keyup: triggered when the keyboard pops up. It is not case sensitive
  2. keydown: triggered when the key is pressed. It is not case sensitive
  3. keypress: triggered when the key is pressed (function keys are not recognized, such as ctrl, shift, etc.), which is case sensitive

(2) keyCode: ASCII code value to judge which key the user presses

case

Picture follow mouse

Knowledge points: mouse move event mousemove

Core idea

  1. Using mouse event mousemove to get the position of mouse in real time
  2. Set two variables, x and y, and assign the real-time coordinates of the mouse to x and y
  3. Set relative positioning for the picture (if there is no absolute positioning, the whole browser will be used for positioning, and the relative positioning does not occupy the position). y and x are assigned to top and left respectively

Note: when assigning the values of x and y to top and left, the unit px should be added in the way of splicing strings. Otherwise, there is no effect.

code

html part
<img src="image/arrow.png" alt="">
css part
<style>
    img {
        position: absolute;
        top: 0;
        left: 0;
    }
</style>
javascript part
<script>
    var jian = document.querySelector('img');
    document.addEventListener('mousemove', function(e) {
        // As long as the mouse moves 1px, the mousemove event is triggered
        // Each time we move the mouse, we need to obtain the coordinates of the mouse in real time and assign them to the top and left of img
        var x = e.pageX;
        var y = e.pageY;
        jian.style.left = x + 'px';
        // Both the top value and the left value have units (e.g. top: 2px). Therefore, it is necessary to add units in the form of concatenated strings in order to operate normally
        jian.style.top = y + 'px';
        // To center the picture, just subtract half the size of the picture after x and y
    })
</script>

Express order No. query

Knowledge points: keyboard events

Core idea

  1. When entering content, the font box (con) above displays (larger font)
  2. Form detection user input: add keyboard event
  3. Assign the value of the document number to the font box
  4. If the document number is empty, the font box is hidden

code

html part
<div class="bg">
    <div class="con"></div>
    <input type="text" placeholder="123">
</div>
css part
<style>
    * {
        margin: 0;
        padding: 0;
        border: 0;
        box-sizing: border-box;
    }
    
    .bg {
        position: relative;
        width: 300px;
        margin: 100px auto;
    }
    
    .con {
        display: none;
        width: 200px;
        height: 30px;
        line-height: 30px;
        font-size: 25px;
        border: 1px solid #ccc;
    }
    
    .con::before {
        content: '';
        width: 0;
        height: 0;
        position: absolute;
        top: 29px;
        left: 15px;
        border: 8px solid #ccc;
        border-style: solid dashed dashed;
        border-color: #ccc transparent transparent;
    }
    
    input {
        position: absolute;
        top: 36px;
        left: 0;
        width: 200px;
        outline: none;
        border: 1px solid #999;
    }
</style>
javascript part
<script>
    var con = document.querySelector('.con');
    var ipt = document.querySelector('input');
    ipt.addEventListener('keyup', function(e) {
            // When the form is not empty, the upper box is displayed and the value is assigned to the box
            if (ipt.value != '') {
                con.style.display = 'block';
                var v = ipt.value;
                con.innerHTML = v;
            } else {
                con.style.display = 'none';
            }
        })
        // If the form loses focus, the box is hidden
    ipt.addEventListener('blur', function(e) {
        con.style.display = 'none';
    })
</script>

effect

By default, the top is not displayed

Lose focus and don't show

JD key input

Knowledge points: keyboard events

Core idea

  1. Judge whether the user presses the s key. If it is pressed, it will be located in the search
  2. Use keycode to judge the key pressed
  3. The search box gets the focus, and the focus() method

code

html part
<input type="text" placeholder="mobile phone">
javascript part
<script>
    var ipt = document.querySelector('input');
    document.addEventListener('keyup', function(e) {
        // Here, both keyup and keydown are OK, but keydown is triggered when pressed. s will be input into input. It will be better to use keyup
        if (e.keyCode == 83) {
            ipt.focus();
        }
    })
</script>

Topics: DOM