Home > Web Front-end > JS Tutorial > JavaScript events

JavaScript events

巴扎黑
Release: 2016-12-06 10:35:52
Original
1232 people have browsed it

前言:原本这篇文章是打算6号书写出来的,但是基于某些私人原因,希望能够通过这篇文章尽可能的将事件讲解的更加详细和通俗易懂,因此,多花了一天时间,不多说了,接下来对“事件”来一个较为详细的介绍。
欢迎大家互相学习交流。独行冰海
需要了解事件的什么?
对于事件来讲,首先,我们需要了解这样几个概念:事件;事件处理程序;事件类型;事件流;事件冒泡;事件捕获;事件对象;事件方面的性能优化(事件委托、移除事件处理程序);常见的浏览器兼容问题。
事件的概念
事件:指的是文档或者浏览器窗口中发生的一些特定交互瞬间。我们可以通过侦听器(或者处理程序)来预定事件,以便事件发生的时候执行相应的代码。
事件处理程序
事件处理程序:我们用户在页面中进行的点击这个动作,鼠标移动的动作,网页页面加载完成的动作等,都可以称之为事件名称,即:click、mousemove、load等都是事件的名称。响应某个事件的函数则称为事件处理程序,或者叫做事件侦听器。
接下来我们用一段代码来再说明一下上面这两个抽象的概念,具体解释见代码注释:



   
    事件-独行冰海


   

理解事件的基本概念


<script><br> var main = document.getElementById('main');<br> // Click here is the name of an event, which is the moment when a click occurs in the browser window . The word on actually allows the click event to respond. Therefore, onclick is called an event handler. In the following code, we reserve a click for the main element through the handler (onclick), so that when the click occurs, the code in the function is executed (a dialog box pops up). <br> main.onclick = function(){<br> alert('Click here!');<br> }<br></script>

About the event handler, from its initial development to the present, experience changed several times.
The name of the event handler starts with "on", so the handler of the click event is onclick. Initially, HTML event handlers were used, that is to say, each event supported by an element (such as a div) could be specified using an HTML attribute with the same name as the corresponding event handler (that is, the tag's an attribute), the value of this attribute is the JavaScript code that can be executed. For example:




Event - Alone in the Ice Sea
< /head>

HTML event handler




Of course, we also You can call the function in onclick="".
However, no matter which method is used, many problems of the HTML event handler are exposed:
First of all, the HTML code domain and the JavaScript code are tightly coupled together and are not separated from each other, which makes it abnormal when updating and maintaining the code. difficulty.
Second, extending the scope chain of event handlers will lead to different results in different browsers.
Third, if you do not use the method of calling functions, but write the code directly as in the example, then the code will have poor versatility, which will make the entire site have a large amount of code and poor versatility. If you extract it and store it in a function, you will face another problem - when the function has not been defined, but the HTML and CSS codes have been loaded, and the user clicks, there will be no response at all.

Based on the above problems, people gradually improved the event handler, and at this time, the DOM0 level event handler appeared. (Appeared in the fourth generation WEB browser)
What does the DOM level 0 event handler look like? In fact, it is our most commonly used event binding, such as the following example:




< title>Event - Alone in the Ice Sea


DOM level 0 event handler



<script> After the launch of the DOM level 0 event handler, it has been widely used by various users. However, a problem arises. When I want to bind multiple events of the same type to the same element/tag (for example, for the above The p tag binds 3 click events), which is not allowed. Then, at this time, another type of event handler appeared, which is the DOM2 level event handler. In the DOM2 level, two basic methods are defined to handle the operations of specifying (i.e. binding) and deleting event handlers. , respectively addEventListener() and removeEventListener(), IE9+, FireFox, Safari, Chrome and Opera all support DOM2-level event handlers. For IE8-, IE's proprietary event handler is used: two similar methods - attachEvent() and detachEvent(). <br>The specific example code is as follows: (taking addEventListener as an example, two writing methods are given)<br><!doctype html><br><html><br><head><br> <meta charset="UTF-8"> <br> <title>Event - Alone in the Ice Sea</title><br></head><br><body><br> <p id='btn'>DOM0 level event handler</p><br>< /body><br><script><br> var btn = document.getElementById('btn');<br> btn.addEventListener("click", test, false);<br>    function test(){<br>        alert(this.innerHTML);<br>    }<br></script>




   
    事件-独行冰海


   

DOM0级事件处理程序



<script><br>    var btn = document.getElementById('btn');<br>    btn.addEventListener("click", function(){<br>        alert(this.innerHTML);        <br>    }, false);<br></script>

addEventListener()和removeEventListener()中的第三个参数,表示的是在哪个事件阶段进行事件处理,如果是false,则指的是冒泡阶段;如果是true,则指的是捕获阶段。
在事件方面,IE与FF存在着一系列的兼容问题,具体问题可查看博文《IE浏览器与FF火狐浏览器在事件上的兼容问题》
关于如何创建一个兼容全部浏览器的事件侦听器,我们在下一篇博文《跨浏览器的事件处理函数——处理DOM2级事件兼容 》当中再做详细的介绍和代码示范。
事件类型
之前在课程的讲解当中,我们把事件分为了三大类,分别是一般事件、表单事件和页面事件。当前我们可以再做细分:
UI事件:如load、unload、error、resize、scroll、select、DOMActive,是用户与页面上的元素交互时触发的。
焦点事件:如blur、DOMFocusIn、DOMFocusOut、focus、focusin、focusout,在元素获得或失去焦点的时候触发,这些事件当中,最为重要的是blur和focus,有一点需要引起注意,这一类事件不会发生冒泡!
鼠标与滚轮事件:如click、dblclick、mousedown、mouseenter、mouseleave、mousemove、mouseout、mouseover、mouseup,是当用户通过鼠标在页面执行操作时所触发的。
滚轮事件:mousewheel(IE6+均支持)、DOMMouseScroll(FF支持的,与mousewheel效果一样)。是使用鼠标滚轮时触发的。
文本事件:textInput,在文档中输入文本触发。
键盘事件:keydown、keyup、keypress,当用户通过键盘在页面中执行操作时触发。
合成事件:DOM3级新增,用于处理IME的输入序列。所谓IME,指的是输入法编辑器,可以让用户输入在物理键盘上找不到的字符。compositionstart、compositionupdate、compositionend三种事件。
变动事件:DOMsubtreeModified、DOMNodeInserted、DOMNodeRemoved、DOMAttrModified、DOMCharacterDataModified等,当底层DOM结构发生变化时触发。IE8-不支持。
变动名称事件:指的是当元素或者属性名变动时触发,当前已经弃用!
对于事件的基本类型,随着HTML5的出现和发展,又新增了HTML5事件、设备事件、触摸事件、手势事件等各种事件,在后面我们再详细介绍。
事件流
事件流:描述的是从页面中接收事件的顺序。
IE与原来的NetScape(网景),对于事件流提出的是完全不同的顺序。IE团队提出的是事件冒泡流;NetScape的事件流是事件捕获流。
事件冒泡
事件冒泡:表示的是,事件开始的时候由最具体的元素(文档中嵌套层次最深的那个节点)接收,然后逐级向上传播到较为不具体的节点(文档)。
事件捕获
事件捕获:表示的是,事件开始的时候由最不具体的节点接收,然后逐级向下传播到最具体的节点。
来看一个实例:



   
    事件-独行冰海


   

       

理解事件的基本概念


   



如果单击了p标签,那么,如果是事件冒泡流的事件流机制,则click事件将按照如下顺序进行执行:p —— div —— body —— html —— document。
如果采用捕获流的事件流机制,则click事件的执行顺序为:document —— html —— body —— div —— p
对于冒泡流的事件流机制,存在如下的兼容问题:
<=IE5.5 p -> div -> body -> document
>=IE6.0        p -> div -> body -> html -> document
>=Mozilla 1.0    p -> div -> body -> html -> document -> window
欢迎大家互相学习交流。独行冰海
事件对象
事件对象:在触发DOM上的某个事件的时候,会产生一个事件对象event,而在这个对象当中会包含着所有与事件有关的信息。我们书写如下基本代码:



   
    事件-独行冰海


   
理解事件的基本概念


<script><br>    var main = document.getElementById('main');<br>    main.onclick = function(event){<br>        console.log(event);<br>    }<br></script>

使用console.log打印出的结果如下图。
JavaScript事件 详细讲解 - 独行冰海 - 独行冰海

其中有两个信息,我们最为常用,分别是type和target。
type表示的是被触发事件的类型;
target表示的是事件的目标。
其他信息,如:
bubbles:表示事件是否冒泡
cancelable:表示是否可以取消事件的默认行为
currentTarget:表示事件处理程序当前正在处理事件的那个元素
defaultPrevented:表示是否调用了preventDefault()
detail:表示的是与事件相关的细节信息
eventPhase:调用事件处理处理程序的阶段:1表示捕获阶段、2表示处于目标、3表示冒泡阶段
在其中还有一些其他信息,在此就不再一一列举了。
事件方面性能优化
谈一谈事件方面如何优化性能——事件委托和事件处理程序的移除
在JavaScript代码当中,添加到页面中的事件越多,页面的性能也就越差。导致这一问题的原因主要有:
每个函数都是对象,都会占用内存。内存中对象越多,性能也就越差。
必须事先指定所有事件处理程序而导致的DOM访问次数,会延迟整个页面的交互就绪时间。
为了进行页面的性能优化,因此我们会采用两种方法,就是上面提到的——事件委托和事件处理程序的移除。
事件委托
很多人问我,什么时候使用事件委托,其实,简单来说,当时一个页面事件处理程序比较多的时候,我们通常情况下会使用它。
事件委托主要利用了事件冒泡,只指定一个事件处理程序,就可以管理一个类型的所有事件。例如:我们为整个一个页面制定一个onclick事件处理程序,此时我们不必为页面中每个可点击的元素单独设置事件处理程序(onclick)。还是,看一个例子。
效果:点击不同的元素执行不同的操作。
不使用事件委托:



   
    事件-独行冰海
   


   

       
        1
        2
        3
       
   


<script><br>    var left = document.getElementById('left');<br>    var first = document.getElementById('first');<br>    var second = document.getElementById('second');<br>    var third = document.getElementById('third');<br>    var right = document.getElementById('right');<br>    left.addEventListener("click", function(){<br>        alert('点击的是左这个字,执行相关操作');        <br>    }, false);<br>    first.addEventListener("click", function(){<br>        alert('要执行第一个序号对应的相关操作');        <br>    }, false);<br>    second.addEventListener("click", function(){<br>        alert('要执行第二个序号对应的相关操作');        <br>    }, false);<br>    third.addEventListener("click", function(){<br>        alert('要执行第三个序号对应的相关操作');        <br>    }, false);<br>    right.addEventListener("click", function(){<br>        alert('点击的是右这个字,执行相关操作');        <br>    }, false);<br></script>

不难看出,我们使用了5个事件侦听器,每设置一个就需要绑定一个。
使用事件委托:



   
    事件-独行冰海
   


   

       
        1
        2
        3
       
   


<script><br> var control = document.getElementById('control');<br> control.addEventListener("click", function(e){<br> ) // Note, IE8- is not considered here If you want to write the event processing procedure compatible with all browsers, check the next blog text <br> var target = e.target; <br> // use the switch statement here, you can also use IF to judge <br> Switch ( target.id){<br>                case "left": {<br>                                                                                                                                                   . <br>                 alert('To execute the first The related operations corresponding to the serial number');<br>                             break; break;<br>             }<br>                   case "third": {<br>                                                     alert('To perform the related operation corresponding to the third serial number');<br>                             break; ');<br>               break;<br> }<br>          }<br>     }, false);<br></script>

Briefly summarize the so-called event delegation: bind events to the parent or ancestor of the element, or even the page, and then use the event to risk The basic principle of bubbles is to detect event target objects and then perform related operations. The advantage is:
It greatly reduces the number of event handlers, and it takes less time to set up event handlers on the page (reduced DOM references - that is, above we use the id to get the tag, the required search operations and the DOM There are even fewer citations).
Document (Note: The above example is not bound to the document, but to the parent div. The most recommended is to bind it to the document) object can be accessed quickly, and can be accessed during the page life cycle Add an event handler for it at any point in time, and there is no need to wait for the DOMContentLoaded or load event. In other words, as long as a clickable element is presented on the page, it immediately has the corresponding functionality.
The entire page will take up less memory space, thereby improving overall performance.
Removing Event Handlers
Whenever an event handler is assigned to an element, a connection is established between the running browser code and the JavaScript code that powers page interaction. The number of connections also directly affects the execution speed of the page. Therefore, when outdated "null event handlers" exist in memory, it will cause memory and performance problems in web applications.
So when will the "empty event handler" appear?
There is an event on the element in the document. This element is removed through some DOM node operations (removeChild, replaceChild, etc. methods), but the event on the DOM node is not removed.
innerHTML replaces a certain part of the page. The original part of the page has an event and is not removed.
The event handler is stuck in memory caused by page unloading.
Solution:
Make reasonable use of event delegation;
When performing related operations, remove the event first, and then remove the DOM node;
Before the page is unloaded, remove all event handlers through the onunload event.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template