El fragmento de código siguiente no combina las funciones setTimeOut y event.key. La ventana serchOverlay se cierra cuando presiona cualquier tecla, pero solo debería cerrarse cuando presiona Escape. Si elimina la función setTimeOut, la ventana se cierra solo presionando Escape. Pero debido a esto, la animación deja de funcionar: la apariencia suave de la superposición. ¿Cómo lidiar con el problema?
function searchClose(event) { searchOverlay.removeAttribute('style'); setTimeout(function () { if (event.key === 'Escape' || !event.target.closest(".search-inner")) { body.classList.remove('is-search-open'); event.stopPropagation(); } }, 200); } searchOverlay.addEventListener('keydown', searchClose); searchOverlay.addEventListener('click', searchClose);Creo que esto es lo que quieres:
function searchClose(event) { /* The only keyboard event that should close the overlay is pressing Esc. Any other keyboard event should do whatever is the browser-default behavior for that event. */ if(event.key && event.key !== 'Escape') return true /* Mouse click should only dismiss the overlay if the click is outside the overlay. */ if(!event.key && !event.currentTarget.closest('.search-inner')) return true /* At this point, we can be certain that this event should close the overlay. */ // task 1: set up a timer that will hide the overlay after a delay setTimeout(closeOverlay, 200) // task 2: consume the event so nothing else reacts to it event.stopPropagation() event.preventDefault() return false } function closeOverlay() { body.classList.remove('is-search-open') } searchOverlay.addEventListener('keydown', searchClose) searchOverlay.addEventListener('click', searchClose)Tenga en cuenta que moví la declaración de cierre de superposición real a su propia función. Ese no es un requisito para que esto funcione, pero creo que hace que este ejemplo de código sea más claro y fomenta la reutilización.