javascript - 在 javascript 中监听自定义事件
问题描述
我正在阅读 MDN 网站上的一篇文章,讨论如何在 javascript https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events中自定义事件,我能够创建这个
const evt = new CustomEvent("swipe", {
detail: {
color: "red"
}
});
documet.addEventListener("swipe", e => {
console.log(e.detail);
});
document.dispatchEvent(evt);
但问题是,事件立即被触发,我怎样才能通过定义swipe
真正的 a 来阻止它?例如,我希望当有人点击屏幕时触发事件,但我仍然想使用这个swipe
词作为它的监听器。
解决方案
...我希望当有人点击屏幕时触发事件...
您将使用click
(或mousedown
)处理程序来触发您的swipe
事件:
document.addEventListener("click", e => {
document.dispatchEvent(new CustomEvent("swipe", {
detail: {
color: "red"
}
}));
});
现场示例:
document.addEventListener("click", e => {
document.dispatchEvent(new CustomEvent("swipe", {
detail: {
color: "red"
}
}));
});
document.addEventListener("swipe", e => {
console.log(e.detail);
});
Click anywhere on the document.