简体   繁体   中英

Javascript - stop a modal keyboard event from bubbling / propagating

I have a page which has a keydown event listener, to listen for the Escape key, to navigate back. I also have a simple modal class, which also listens for the Escape key to close it. The main page listener checks if a modal is open, and if so, returns without doing anything.

window.addEventListener("keydown", function (ev) {
                                           if (modal_is_open) { return; }
                                           ev = ev || window.event;
                                           if (ev.key == "Escape") { history.go(-1); }
                                         });

modal_div.addEventListener("keydown",function (ev) {
                                           ev = ev || window.event;
                                           ev.stopPropagation();
                                           ev.preventDefault();
                                           ev.cancelBubble = true;
                                           if (ev.key == "Escape") { close_the_modal(); }
                                           return false;
                                         });

My problem is, if a modal is open, the Escape key closes it, but still bubbles up to the main page handler and navigates back. How can I stop this?

我终于找到了解决方案,将stopPropagation替换为stopImmediatePropagation ,如果模态打开,则窗口 keydown 处理程序不再触发。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM