Talk about JavaScript events

What is an 'event'?

The user's behavior on the web page is called an event

The purpose of the learning event: I hope to customize it so that users can execute and write a piece of code after performing a certain behavior on the web page.

grammar:

1.Event source.on event type=function() {}

2. Inline binding: <tag on event type="a line of js code or function call"> </tag>

3.Event source.addEventListener('event type',function() {})

Note: The event source refers to which tag is used when the event is triggered. Remember to get the tag first.

event type

The event type refers to the behavior the user is performing

Event types are mainly divided into four categories: mouse, keyboard, form, and window.

1. Mouse class

Click---click

Double click---dbclick

移入---mouseover/mouseenter

移出---mouseout/mouseleave

Mouse down---mousedown

Release the mouse---mouseup

Mouse movement---mousemove

Rolling wheel---mousewheel

Right click---contextmenu

Second keyboard type

Keyboard press---keydown---- will keep triggering if you don't release it.

Keyboard lift---keyup----used frequently

Keystroke---keypress

3. Form class

Get focus---focus

Lost focus---blur

The drop-down box option changes event --change

Form submission---submit

Note: The form tag must be bound;

When will the submit event be triggered?

Answer: Triggered when the submit button in the form field (the input type is submit, or the button type is submit) is clicked or hit Enter)

input event----monitor the event of the content in the text box or text field in real time

4. Window class

The loading event --load-- will only be triggered when all resources in the page have been loaded.

Scroll bar scroll event--scroll- will be triggered when the scroll bar scrolls;

Window size change event--resize--will be triggered when the size of the browser changes

Main matters

The difference between mouseover() and mouseenter() (execute mouseover first and then mouseenter)

The mouseover event is triggered when the mouse moves over the selected element and its child elements.
The mouseenter event is only triggered when the mouse moves over the selected element.

The mouseover/mouseout event supports bubbling, and the bound event will bubble up to the child tag.
The mouseenter/mouseleave event only targets the bound label and will not bubble up to sub-labels. 

(mouseover will also be executed when entering the child element, while mouseenter will only execute the bound element, and will not be executed when entering the child element)

With mouseover, you can see elements entering the parent set, entering the subset, and then leaving the subset and entering the parent, three times in total.

And mouseout only occurs once when entering the parent level.
 

 event stream

When each event occurs, there will be a triggering and execution process, which is the propagation process of the event, which we call event flow.

Simply put, event flow is the process from the occurrence of an event to the end of its execution.

The event flow consists of 3 stages: capture stage, target stage, and bubbling stage.

Event capture phase: The event starts to be triggered by the top-level element, and then propagates downwards step by step until it reaches the target element, and the events bound to it are executed in sequence.

Event target stage (processing stage): trigger the current own event.

Event bubbling stage: The event is first received by the target element, and then propagated upward step by step, reaching the top element, and the events bound to it are executed in sequence.

The process of event execution is first the capture stage ---> then the target element stage --> and finally the bubbling stage.

Events of the target element are executed in the target phase, and other events are executed in the bubbling phase. Each event will only be executed once, which means that if the event is executed during the bubbling phase, it will not be executed during the capture phase.

How to bind events

The first type: label.on event type=function() {}

 The second is the event listener 

tag.adddEventListener('event type', function, boolean - whether to execute in the capture phase)

 If the Boolean parameter is true, it means that the event handler is called during the capture phase; if it is false, it means that the event handler is called during the bubbling phase.

example:

The benefits of event listeners are twofold: 1. Events can be executed during the capture phase 2. Events of the same type can be bound multiple times without overwriting

unbundling of events

Because event binding stores events in memory, but this event is no longer needed after the event is executed, then you need to unbind it.

The unbinding method can be based on the binding method:

1. Tag.on type=null

example

var btn = document.querySelector('button')
// console.dir(btn);

 btn.onclick = function() {
    console.log(111);
     // delete this.onclick // 删除对象的onclick属性

   this.onclick = null
//     console.dir(this);

2. If the tag.addEventListenter() type is used, you must use the tag.removeEventListener()

example:

  btn.addEventListener('click', function () {
        console.log('nihao')
    })

important point

  Summary:
    1. What is the essence of binding events? Assign the event type to a function and store it in memory.
    2. Why unbind? Some events are no longer required after execution.
    3. How to unbind?
        Depending on the binding method, the unbinding method is also different:
        1. If it is bound using tag.on type, give tag.on type = null
        2. If it is bound using an event listener, use tag.removeEventListener( Event type, corresponding function)
        If the bound function is an anonymous function, this event cannot be unbound
 

event object

Concept: An event object is an object provided by the system to record event-related information.

Obtain: window.event in the event   !! Note : the event object of each event is different, so the event object must be obtained in the event function

The role of event objects

1. Get the event type: event object.type

example:

  btn.addEventListener('click', function () {

        var e = window.event;

        console.log(e.type)//click

        console.log('nihao')

    })

2. Get mouse button information: event object.button

(Event object.button represents the current mouse button information: 0 left button 1 wheel 2 right button)

 window.onmousedown = function () {
        var e = window.event;
        console.log(e.button)
    }

3. Prevent event bubbling: event object.cancelBubble=true

4. Get the information key code of the keyboard keys

Key code: event object.keyCode

The key codes for numbers and letters are Asker codes

The enter key code is 13; the space code is 32; the key codes for the upper left and lower right are: 37, 38, 39, 40;

important point:

Use the event object .which in older versions of Firefox to obtain the key code

So when dealing with compatibility, you can var keycode = e.keyCode || e.which

to handle compatibility issues

Key combination:

event object.ctrlKey

event object.altKey

event object.shiftKey

Note: The output values ​​are all Boolean values, representing whether to hold down the corresponding key.

5. Get the mouse position;

Relative to the event source: event object.offsetX; event object.offsetY

Relative to the browser window: event object.clientX; event object.clientY;

Relative to the entire page: event object.pageX; event object.pageY;

var box = document.querySelector('.box');
// box.onclick = function() {
//     var e = window.event;
//     // 1.获取鼠标在当前事件源上点击的位置
//     // 事件对象.offsetX 事件对象.offsetY
//     var x1 = e.offsetX
//     var y1 = e.offsetY
//     // console.log(x1, y1);

//     // 2.获取鼠标在当前浏览器区域中的位置
//     // 事件对象.clientX 事件对象.clientY
//     var x2 = e.clientX
//     var y2 = e.clientY
//     // console.log(x2, y2);

//     // 3.获取鼠标在当前页面中的位置
//     // 事件对象.pageX 事件对象.pageY
//     var x3 = e.pageX
//     var y3 = e.pageY
//     console.log(x3, y3);
// }

6. Prevent default behavior;

1.Event object.returnValue=false;

2. Add return false at the bottom of the event function;

3. If there is a link, change the link to: JavaScript:;

 // 默认行为:自带的功能
    // 有些标签不需要使用js事件操作,自动就能实现某些功能,例如a标签、form、鼠标右击

    // 阻止默认行为
    var a = document.querySelector('a');
    a.onclick = function () {
        // 利用事件对象,阻止默认行为
        var e = window.event;
        // 1.阻止默认行为 - 事件对象.returnValue = false
        e.returnValue = false
        console.log(11);
        // 2.在事件函数的末尾,添加  return false
        // return false
    }

7. Obtain a specific and more accurate target element: event object.target

At this point, what event is delegated ?

 Event delegation: Using the principle of event bubbling, let the parent tag handle the event instead of the child tag.

 How to do event delegation? Bind an event to the parent tag. In the parent tag event, obtain the target sub-tag that currently triggers the event through the event object.target, and handle this behavior.

    benefit:

    1. Improve binding efficiency

    2. Dynamically added sub-tags can also have events

example

<body>
<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

There are three li tags here. We now need to bind a click event to each li. Then we bind a click event to each li by traversing lis.

var lis = document.querySelectorAll('li');
 for(var i=0; i<lis.length;i ++) {
     lis[i].onclick = function() {
         console.log(this.innerText);
     }
 }

Here we can use event delegation to handle this request;

When we click on li, we are actually clicking on ul; so just bind the click event to ul.

var ul = document.querySelector('ul');
ul.onclick = function() {
    // console.log('哈哈');
    // 如何在父标签的事件中找到当前正在点击的子标签
    // 事件对象中有一个属性 target,可以获取到当前点击的更加精准的目标元素
    console.log( window.event.target.innerText );
}

Guess you like

Origin blog.csdn.net/weixin_45441470/article/details/123718403