<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button type="button" name="button" class="test" id="btn1">Event方式自定义事件</button> <button type="button" name="button" class="test" id="btn2">CustomEvent方式自定义事件</button> <button type="button" name="button" class="test" id="btn3">兼容IE的自定义事件</button> </body> <script> 方式一:浏览器都兼容的性质,但是目前官网不建议用; var button3 = document.getElementById('btn3'); var create = document.createEvent('Event'); create.initEvent('create',false, false); document.addEventListener('create',function (e) { alert('兼容IE的自定义事件顺利触发') }); button3.addEventListener('click',function () { document.dispatchEvent(create) }); 方式二:使用Event类自定义事件 var button = document.getElementById('btn1'); var selfEvent = new Event('self',{ "bubbles": true,//事件是否冒泡 "cancelable": false,//事件是否支持取消 "composed": false//事件是否在阴影根之外 }); //监听 document.addEventListener('self',function (e) { alert('Event自定义事件被顺利触发') }); //触发 button.addEventListener('click',function () { document.dispatchEvent(selfEvent) }); 方式三:使用CustomEvent类自定义事件 var button2 = document.getElementById('btn2'); var custom = new CustomEvent('custom',{ detail:{ age: 18 },//detail对象是比旭要有的 "bubbles": true, "cancelable": false }); document.addEventListener('custom',function () { alert('CustomEvent自定义事件被顺利触发') }); button2.addEventListener('click',function () { document.dispatchEvent(custom) }); </script> </html>