事件触发顺序
捕获和冒泡
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Dom 事件 </title>
- <style>
- #layer{
- width: 300px;
- height: 200px;
- background-color: #c03035;
- }
- </style>
- <script>
- window.onload = function(){
- var layer = document.getElementById("layer");
- window.addEventListener('click', function(){
- console.log("点击事件被 window 捕获");
- }, true);
- document.addEventListener('click', function(){
- console.log("点击事件被 document 捕获");
- }, true);
- document.documentElement.addEventListener('click', function(){
- console.log("点击事件被 HTL 获取")
- }, true);
- document.getElementsByTagName('body')[0].addEventListener('click', function () {
- console.log('点击事件被 Body 捕获')
- },true);
- document.getElementById("layer").addEventListener('click', function(){
- console.log("点击事件被 div 捕获");
- }, true);
- window.addEventListener('click', function(){
- console.log("点击事件冒泡到 window");
- }, false);
- document.addEventListener('click', function(){
- console.log("点击事件冒泡到 document");
- }, false);
- document.documentElement.addEventListener('click', function(){
- console.log("点击事件冒泡到 HTML")
- }, false);
- document.getElementsByTagName('body')[0].addEventListener('click', function () {
- console.log('点击事件冒泡到 Body')
- },false);
- document.getElementById("layer").addEventListener('click', function(){
- console.log("点击事件冒泡到 div");
- }, false)
- };
- </script>
- </head>
- <body>
- <div id="layer">
- 1234
- </div>
- </body>
- </html>
利用事件捕捉进行错误监控
加载了不存在的 js 文件, 事件被捕获
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title > 利用事件捕获记录 js 加载出错 </title>
- <script>
- // 在事件捕获阶段打印函数
- window.addEventListener('error', function (ev) {
- console.log(ev);
- }, true);
- </script>
- <script src="./sdfasdf.js"></script>
- <script src="./asdf.js"></script>
- </head>
- <body>
- </body>
- </html>
自定义事件的写法
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
自定义事件
- </title>
- <script>
- window.onload = function(ev) {
- // 自定义事件
- var cusE = new Event('customEvent');
- // 获取一个元素
- var my_div = document.getElementById("my_div");
- // 绑定事件
- my_div.addEventListener('customEvent',
- function() {
- console.log("自定义事件被执行!");
- });
- // 当元素被点击时, 触发自定义事件
- my_div.addEventListener('click',
- function() {
- console.log("div 元素被点击!");
- my_div.dispatchEvent(cusE);
- });
- }
- </script>
- <style>
- #my_div{ width: 300px; height: 500px; background-color: #d29922; }
- </style>
- </head>
- <body>
- <div id="my_div">
- </div>
- </body>
- </html>
来源: http://www.jianshu.com/p/e5375bda58da