The content of this article is about commonly used event analysis in browsers. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Triggered when the value of <input>
, <textarea>
changes . In addition, if the element with the contenteditable attribute is turned on, the input event will also be triggered whenever the value changes. One characteristic of the input event is that it will be triggered continuously. For example, every time the user presses a button, an input event will be triggered.
Such events include: keydown, keyup,
select events are triggered when text is selected in <input>, <textarea>
change event is triggered when the value of <input>,
Triggered when the radio or checkbox is activated.
Triggered when user submits. For example, complete the selection from the following list (select), complete the selection in the date or file input box.
Triggered when the value of the text box or textarea element changes and the focus is lost.
The reset event is triggered by the form element when the form is reset (all form members are changed back to their default values).
The submit event is triggered by the form element when the form data is submitted to the server.
The beforeunload event is triggered when the window is about to be closed, or when the document and web page resources are about to be unloaded. It can be used to prevent users from accidentally closing a web page. The default action of this event is to close the current window or document. If event.preventDefault() is called in the listening function, or a non-null value is assigned to the returnValue attribute of the event object, a confirmation box will automatically pop up to allow the user to confirm whether to close the web page. If the user clicks the "Cancel" button, the web page will not close. The string returned by the listening function will be displayed in the confirmation dialog box:
window.addEventListener('beforeunload', function(event) { if(event.preventDefault){ event.preventDefault(); } else { event.returnValue = '你确认要离开吗?'; } });
unload events are triggered when the window is closed or the document object is about to be unloaded. They occur in window, above body, frameset and other objects. Its triggering order is behind the beforeunload and pagehide events. The unload event will only be triggered when the page has not been cached by the browser. In other words, if the page is unloaded by pressing "Forward/Back", the unload event will not be triggered. When the unload event occurs, the document object is in a special state. All resources still exist, but are not visible to the user, and all UI interactions (window.open, alert, confirm methods, etc.) are invalid. Even if an error is thrown at this time, the unloading of the document cannot be stopped.
The load event is triggered when the page loads successfully, and the error event is triggered when the page fails to load. Note that the page is loaded from the browser cache and does not trigger the load event.
These two events are actually progress events, which occur not only in the document object, but also in various external resources. Browsing the web is a process of loading various resources, such as images, style sheets, scripts, videos, audios, Ajax requests (XMLHttpRequest), etc. These resources, document objects, window objects, and XMLHttpRequestUpload objects will trigger load events and error events.
pageshow event, pagehide event: By default, the browser will cache the page in the current session (session). When the user clicks the "Forward/Back" button, the browser The page will be loaded from cache.
The pageshow event is triggered when the page is loaded, including the first load and loading from cache. If you want to specify code to run every time the page is loaded (whether it is cached from the browser or not), you can place it in the listening function of this event. When loading for the first time, its firing order is behind the load event. When loading from the cache, the load event will not be triggered because the page in the cache usually looks like it does after the load event's listening function is run, so there is no need to repeat it. In the same way, if the page is loaded from the cache, the JavaScript script initialized in the web page (such as the listening function of the DOMContentLoaded event) will not be executed. The pageshow event has a persisted attribute, which returns a boolean value. When the page is loaded for the first time, this attribute is false; when the page is loaded from the cache, this attribute is true.
document.onpageshow = function(event){} if(event.persisted){ //如果存缓存加载 } }
Similarly, setting this attribute to true means that the page will be saved in the cache; setting it to false means that the page will not be saved in the cache. At this time, if a listening function for the unload event is set, the The function will run immediately after the pagehide event. If the page contains a frame, the pageshow event and pagehide event of the frame page will be triggered before the main page.
DOMContentLoaded 事件当 HTML 文档下载并解析完成以后,就会在 document 对象上触发 DOMContentLoaded 事件。这时,仅仅完成了 HTML 文档的解析(整张页面的DOM生成),所有外部资源(样式表, 脚本, iframe等等)可能还没有下载结束。也就是说,这个事件比 load 事件,发生时间早得多。注意,网页的 JavaScript 脚本是同步执行的,所以定义 DOMContentLoaded 事件的监听函数,应该放在所有脚本的最前面。否则脚本一旦发生堵塞,将推迟触发 DOMContentLoaded 事件。此外,IE8 不支持 DOMContentLoaded 事件,可以使用 readystatechange 事件代替。
readystatechange 事件发生在 Document 对象和 XMLHttpRequest 对象,当它的 readyState 属性发生变化时触发。
上面重点提到了 DOMContentLoaded, readystatechange, pageshow, pagehide, unload, load 和 beforeunload 事件,此外还有一下事件:
onafterprint: 文档打印之后运行的脚本
onbeforeprint: 文档打印之前运行的脚本
onbeforeunload: 文档卸载之前运行的脚本(上文已涉及)
onerror: 在错误发生时运行的脚本
onhaschange: 当文档已改变时运行的脚本
onload: 页面结束加载之后触发(上文已涉及)
onmessage: 在消息被触发时运行的脚本
onoffline: 当文档离线时运行的脚本
ononline: 当文档上线时运行的脚本
onpagehide: 当窗口隐藏时运行的脚本(上文已涉及)
onpageshow: 当窗口成为可见时运行的脚本(上文已涉及)
onpopstate: 当窗口历史记录改变时运行的脚本
onredo: 当文档执行撤销(redo)时运行的脚本
onresize: 当浏览器窗口被调整大小时触发
onstorage: 在 Web Storage 区域更新后运行的脚本
onundo: 在文档执行 undo 时运行的脚本
onscroll: 事件在文档或文档元素滚动时执行脚本
new MouseEvent(typeArg, mouseEventInit);
内置的鼠标事件包括:
mousedown: 按下鼠标
mouseup: 鼠标抬起
click: 点击
dblclick: 双击
mousemove: 鼠标移动
mouseover: 鼠标移入,冒泡
mouseout: 鼠标移出,冒泡
mouseenter: 鼠标移入,不冒泡
mouseleave: 鼠标移出,不冒泡
contextmenu: 右键菜单
wheel: 滚轮事件
其具有如下常用属性:
altKey,ctrlKey,metaKey,shiftKey属性返回一个布尔值,表示鼠标事件发生时,是否按下某个键;
button 返回事件的鼠标键信息, 值为0(左键), 1或4(中键, 4为IE中的值),2(右键),可通过switch来选择执行分之);
buttons 属性返回一个3个比特位的值,表示同时按下了哪些键
clientX,clientY 返回鼠标位置相对于浏览器窗口左上角的坐标,单位为像素
screenX,screenY 返回鼠标位置相对于屏幕左上角的坐标,单位为像素
movementX,movementY 返回一个位移,单位为像素,表示当前位置与上一个 mousemove 事件之间的距离,在数值上:
relatedTarget属性返回事件的次要相关节点,即和target属性对应的节点,如: mouseout target 指将要离开的节点,relatedTarget 指将要进入的节点。对于那些没有次要相关节点的事件,该属性返回null
wheel 事件是与鼠标滚轮相关的事件,浏览器提供一个 WheelEvent 构造函数 new WheelEvent(typeArg, mouseEventInit)
deltaX: 返回一个数值,表示滚轮的水平滚动量
deltaY: 返回一个数值,表示滚轮的垂直滚动量
deltaZ: 返回一个数值,表示滚轮的Z轴滚动量
deltaMode: 返回一个数值,表示滚动的单位,适用于上面三个属性。0表示像素,1表示行,2表示页
构造函数 new KeyboardEvent(typeArg, KeyboardEventInit)
键盘事件包括keydown(按下键盘时触发该事件),keypress(只要按下的键并非Ctrl, Alt, Shift和Meta,就接着触发keypress事件), keyup(松开键盘时触发该事件)
altKey,ctrlKey,metaKey,shiftKey: 返回一个布尔值,表示是否按下对应的键
key: 返回一个字符串,表示按下的键名。如果同时按下一个控制键和一个符号键,则返回符号键的键名
keyCode: 返回按键的 ASCII 码,注意: 这里是不区分大小写的,A键
不论输出 A 还是 a keyCode 都是68。在 IE 中使用 witch 属性
new ProgressEvent(type, { lengthComputable: aBooleanValue, // false as default loaded: aNumber, // 0 as default total: aNumber // 0 as default });
进度事件用来描述一个事件进展的过程,比如XMLHttpRequest对象发出的HTTP请求的过程, <img>
, <audio>
, <video>
, <style>
, <link>
加载外部资源的过程,包括下载和上传。通常包括以下事件:
abort事件: 当进度事件被中止时触发。如果发生错误,导致进程中止,不会触发该事件。
error事件: 由于错误导致资源无法加载时触发,不会冒泡。error 事件的监听函数最好放在如 img 元素的 HTML 属性中。
load事件: 进度成功结束时触发。
loadstart事件: 进度开始时触发。
loadend事件: 进度停止时触发,发生顺序排在error事件abort事件load事件后面。loadend事件的监听函数可以用来取代abort事件/load事件/error事件的监听函数,loadend事件本身不提供关于进度结束的原因,但可以用它来做所有进度结束场景都需要做的一些操作。
progress事件: 当操作处于进度之中,由传输的数据块不断触发。
timeout事件: 进度超过限时触发
这类事件具有以下属性:
lengthComputable: 返回一个布尔值,表示当前进度是否具有可计算的长度。如果为false,就表示当前进度无法测量。
total: 返回一个数值,表示当前进度的总长度。如果是通过 HTTP 下载某个资源,表示内容本身的长度,不含 HTTP 头部的长度。如果 lengthComputable 属性为 false,则 total 属性就无法取得正确的值。
loaded: 返回一个数值,表示当前进度已经完成的数量。该属性除以total属性,就可以得到目前进度的百分比。
//进度计算 if (e.lengthComputable){ var percentComplete = e.loaded / e.total; }
new DragEvent(type, DragEventInit);
拖拽指的是,用户在某个对象上按下鼠标键不放,拖动它到另一个位置,然后释放鼠标键,将该对象放在那里。拖拽的对象有好几种,包括 Element 节点, 图片, 链接, 选中的文字等等。在 HTML 网页中,除了 Element 节点默认不可以拖拽,其他(图片, 链接, 选中的文字)都是可以直接拖拽的。为了让 Element 节点可拖拽,可以将该节点的 draggable 属性设为 true。draggable 属性可用于任何 Element 节点,但是图片(img 元素)和链接(a 元素)不加这个属性,就可以拖拽。对于它们,用到这个属性的时候,往往是将其设为 false,防止拖拽。注意,一旦某个 Element 节点的 draggable 属性设为 true,就无法再用鼠标选中该节点内部的文字或子节点了。
当Element节点或选中的文本被拖拽时,就会持续触发拖拽事件,包括以下一些事件:
drag事件: 拖拽过程中,在被拖拽的节点上持续触发。
dragstart事件: 拖拽开始时在被拖拽的节点上触发,该事件的target属性是被拖拽的节点。通常应该在这个事件的监听函数中,指定拖拽的数据。
dragend事件: 拖拽结束时(释放鼠标键或按下escape键)在被拖拽的节点上触发,该事件的target属性是被拖拽的节点。它与dragStart事件,在同一个节点上触发。不管拖拽是否跨窗口,或者中途被取消,dragend事件总是会触发的。
dragenter事件: 拖拽进入当前节点时,在当前节点上触发,该事件的target属性是当前节点。通常应该在这个事件的监听函数中,指定是否允许在当前节点放下(drop)拖拽的数据。如果当前节点没有该事件的监听函数,或者监听函数不执行任何操作,就意味着不允许在当前节点放下数据。在视觉上显示拖拽进入当前节点,也是在这个事件的监听函数中设置。
dragover事件: 拖拽到当前节点上方时,在当前节点上持续触发,该事件的target属性是当前节点。该事件与dragenter事件基本类似,默认会重置当前的拖拽事件的效果(DataTransfer对象的dropEffect属性)为none,即不允许放下被拖拽的节点,所以如果允许在当前节点drop数据,通常会使用preventDefault方法,取消重置拖拽效果为none。
dragleave事件: 拖拽离开当前节点范围时,在当前节点上触发,该事件的target属性是当前节点。在视觉上显示拖拽离开当前节点,就在这个事件的监听函数中设置。
drop事件: 被拖拽的节点或选中的文本,释放到目标节点时,在目标节点上触发。注意,如果当前节点不允许drop,即使在该节点上方松开鼠标键,也不会触发该事件。如果用户按下Escape键,取消这个操作,也不会触发该事件。该事件的监听函数负责取出拖拽数据,并进行相关处理。
关于拖拽事件,有以下几点注意事项:
拖拽过程只触发以上这些拖拽事件,尽管鼠标在移动,但是鼠标事件不会触发。
将文件从操作系统拖拽进浏览器,不会触发 dragStart 和 dragend 事件。
dragenter 和 dragover 事件的监听函数,用来指定可以放下(drop)拖拽的数据。由于网页的大部分区域不适合作为 drop 的目标节点,所以这两个事件的默认设置为当前节点不允许 drop。如果想要在目标节点上 drop 拖拽的数据,首先必须阻止这两个事件的默认行为,或者取消这两个事件。
<p ondragover="return false"> //或 <p ondragover="event.preventDefault()">
拖拽事件用一个 DragEvent 对象表示,该对象继承 MouseEvent 对象,DragEvent 对象只有一个独有的属性 dataTransfer,其他都是继承的属性。dataTransfer 属性用来读写拖拽事件中传输的数据,所有的拖拽事件都有一个 dataTransfer 属性,用来保存需要传递的数据,这个属性的值是一个 DataTransfer 对象。拖拽的数据保存两方面的数据: 数据的种类(又称格式)和数据的值。数据的种类是一个MIME字符串,比如 text/plain 或者 image/jpg,数据的值是一个字符串;
dataTransfer 对象的属性的值是一个对象,其中包括以下属性:
dropEffect 属性: 设置放下(drop)被拖拽节点时的效果,可能的值包括 copy(复制被拖拽的节点), move(移动被拖拽的节点), link(创建指向被拖拽的节点的链接), none(无法放下被拖拽的节点)。设置除此以外的值,都是无效的。
effectAllowed 属性: 设置本次拖拽中允许的效果,可能的值包括 copy, move, link, copyLink, copyMove, linkMove, all, none, uninitialized(默认值,等同于 all)。如果某种效果是不允许的,用户就无法在目标节点中达成这种效果。
files 属性: 是一个 FileList 对象,包含一组本地文件,可以用来在拖拽操作中传送。如果本次拖拽不涉及文件,则属性为空的 FileList 对象。通过files属性读取拖拽文件的信息。如果想要读取文件内容,就要使用 FileReader 对象。
types 属性: 是一个数组,保存每一次拖拽的数据格式,如'text/uri-list'
setData() 方法: 用来设置事件所带有的指定类型的数据。它接受两个参数,第一个是数据类型,第二个是具体数据。如果指定的类型在现有数据中不存在,则该类型将写入types属性;如果已经存在,在该类型的现有数据将被替换。
event.dataTransfer.setData("text/plain", "Text to drag");
getData() 方法接受一个字符串(表示数据类型)作为参数,返回事件所带的指定类型的数据(通常是用 setData 方法添加的数据)。如果指定类型的数据不存在,则返回空字符串。
event.dataTransfer.getData(types[0]);
clearData() 方法接受一个字符串(表示数据类型)作为参数,删除事件所带的指定类型的数据。如果没有指定类型,则删除所有数据。如果指定类型不存在,则原数据不受影响。
event.dataTransfer.clearData("text/uri-list");
setDragImage() 可以用来自定义这张图片,它接受三个参数,第一个是img图片元素或者canvas元素,如果省略或为null则使用被拖动的节点的外观,第二个和第三个参数为鼠标相对于该图片左上角的横坐标和右坐标。
event.dataTransfer.setDragImage(img, 0, 0);
new Touch(touchInit);
触摸事件包括以下5种:
touchstart: 用户接触触摸屏时触发,它的 target 属性返回发生触摸的 Element 节点(IE10+中使用 mspointerdown 事件);
touchend: 用户不再接触触摸屏时(或者移出屏幕边缘时)触发,它的 target 属性与 touchstart 事件的 target 属性是一致的,它的 changedTouches 属性返回一个TouchList对象,包含所有不再触摸的触摸点(Touch对象)(IE10+中使用 mspointerup 事件);
touchmove: Triggered when the user moves the touch point. Its target attribute is consistent with the target attribute of the touchstart event. This event will also be triggered if the radius, angle, and intensity of the touch change. (The mspointermove event is used in IE10);
touchenter: Triggered when the touch enters an element. There is no bubbling process for this event. (The mspointerover event is used in IE10);
touchleave: Triggered when the touch point leaves an element. There is no bubbling process for this event. (The mspointerout event is used in IE10);
touchcancel: Triggered when the contact is interrupted for some reason. There are several possible reasons as follows (the specific reasons vary according to different devices and browsers): (There is no corresponding event in IE10);
The touch was canceled due to an event: for example, the touch process was interrupted by a modal pop-up box or phone call;
The touch point left the document window and entered the browser's Interface elements, plug-ins or other external content areas;
When the number of contacts generated by the user exceeds the number supported by the device, the earliest Touch object in the TouchList will be cancelled.
The Touch API consists of three objects. Each Touch object represents a touch point; each touch point is described by its position, size, shape, pressure level, and target element. A TouchList object represents a list of multiple touch points. Specifically, it includes the following attributes:
identifier attribute: Represents the unique identifier of the touch instance. It remains unchanged during the entire touch process (pointerId attribute is used in IE10);
screenX/screenY attributes: respectively represent the abscissa and ordinate of the touch point relative to the upper left corner of the screen, It has nothing to do with whether the page is scrolled;
clientX/clientY attributes: respectively represent the abscissa and ordinate of the touch point relative to the upper left corner of the browser viewport, regardless of whether the page is scrolled;
pageX/pageY attributes: respectively represent the abscissa and ordinate of the touch point relative to the upper left corner of the current page, including the displacement caused by page scrolling;
radiusX/radiusY attribute: Returns the X-axis and Y-axis of the affected ellipse range around the touch point respectively, in pixels;
举一个简单例子:
function handleMove(evt) { evt.preventDefault(); // 阻止浏览器继续处理触摸事件,也阻止发出鼠标事件 var touches = evt.changedTouches; for (var i = 0; i < touches.length; i++) { var id = touches[i].identifier; var touch = touches.identifiedTouch(id); console.log(touch.pageX, touch.pageY); } }
对于跨平台交互,我封装了一个 tap相关事件如下:
//以下代码并未兼容低版本 IE function addTapListener(node, callback){ var startEvent = window.onmousedown ? window.onmspointerdown ? 'mspointerdow' : 'mousedown' : 'touchstart'; var event = window.onclick ? 'click' : 'touch'; var endEvent = window.onmouseup ? 'mouseup' : 'touchend'; node.addEventListener(startEvent, function(e){ var tap = document.createEvent('CustomEvent'); tap.initCustomEvent('tapstart', true, true, null); node.dispatchEvent(tap); }); node.addEventListener(event, function(e){ var tap = document.createEvent('CustomEvent'); tap.initCustomEvent('tap', true, true, null); node.dispatchEvent(tap); }); node.addEventListener(endEvent, function(e){ var tap = document.createEvent('CustomEvent'); tap.initCustomEvent('tapend', true, true, null); node.dispatchEvent(tap); }); node.addEventListener('tap', callback); }
当然本文仅仅列举了一些常用事件,其实事件还有很多,本文会在必要的时候继续更新,但即便如此也不可能穷尽所有的事件,比如还有动画事件: animationstart, animation, animationend 等等。
相关推荐:
解析javascript 浏览器关闭事件_javascript技巧
The above is the detailed content of Analysis of 5 commonly used events in browsers. For more information, please follow other related articles on the PHP Chinese website!