<body>
<div style="width:400px;height:400px;background:blueviolet"></div>
<button id="btn1">搞事</button> <button id="btn2">取消</button>
<script>
let event = new Event("搞事");
let div = document.querySelectorAll("div")[0];
let btn1 = document.getElementById("btn1");
let btn2 = document.getElementById("btn2");
function dosomething(){
console.log("有人在搞事情!");
}
div.addEventListener("搞事",dosomething)//绑定自定义事件
btn1.onclick = function(){
div.dispatchEvent(event);//触发自定义事件
}
btn2.onclick = function(){
div.removeEventListener("搞事",dosomething);//接触绑定的自定义事件
}
</script>
</body>