考虑堆叠层上下文如何处理javascript键绑定?

ena*_*upe 10 html javascript css keyboard dom

让我说我有<body>一个full modal打开.按[ESC]键可关闭此模态.在此范围内full modal,用户可以打开另一个较小的模态,也可以通过按[ESC]键关闭.你如何处理[ESC]键并关闭'更高'层,阻止按键传播并关闭正在收听按键的其他层?

我期待一个直接的答案,使用preventDefault或类似的东西..我不打算设置某种服务,在决定应该关闭哪一层之前进行许多检查..对我来说,这件事应该有点像点击事件,向上传播.这可行吗?

Mac*_*acK 7

没有直接.preventDefault()或一些黑魔法可以阻止你阻止冒泡到事件监听器,除非你想要每次想要为那个不干扰其他处理程序的模态专门附加一个事件监听器时创建一个新的处理程序.

而不是拥有一个处理程序数组和许多事件监听器,为什么不将模块堆叠在一个数组中然后逐个销毁呢?

这是我能想到的最短代码,请参阅代码中的注释以获得逐步说明.

// Global variable, we use this to store DOM objects.
var modalStack = [];

// My function to create/open my modals.
function openModal() {
    var modalHTML = '<div id="modal-'+modalStack.length+'" class="modal"><button onclick="openModal()">Open modal '+(modalStack.length+1)+'</button></div>'; // I populate the modal with my stuff and assign it an ID containing the current stack size. 
    document.body.insertAdjacentHTML( 'beforeend', modalHTML ); // Add into the body
    modalStack.push( document.getElementById('modal-'+modalStack.length) ); // And push my DOM object I just created into the array.
}


// My ESC event listener
window.addEventListener('keyup', function(event) {
    var lastIndex = modalStack.length-1; // This gets the last element on the stack.
    if (event.keyCode == 27 && lastIndex >= 0) {
        var thisModal = modalStack[ lastIndex ]; // Just to make sense, I could've called the removeChild directly from the array.
        thisModal.parentNode.removeChild(thisModal); // Destroy the current element.
        modalStack.pop(); // Remove the associated last DOM object from the array.
    }
}, false);
Run Code Online (Sandbox Code Playgroud)

jsFiddle演示