我有一个 javascript window.open 弹出窗口,我希望当用户按 ESC 键时弹出窗口自行关闭。我不知道如何挂钩 keydown 事件(以及在什么对象上?)以便我可以捕获 ESC 键。
我正在使用 jQuery。
尝试这样的事情:
$(document).keydown(function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
不用jQuery,用JS就可以实现。
window.onkeydown = function( event ) {
if ( event.keyCode == 27 ) {
console.log( 'escape pressed' );
}
};
不再有任意数字代码!
document.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; in ES6+
if (key === "Escape") {
window.close();
}
});
请记住,您必须在弹出窗口中使用函数@Gumbo posts...因此您需要在弹出窗口中包含 JQuery 并在那里执行该函数,而不是打开弹出窗口的窗口。
处理对话框中的 esc 和 Enter 键
window.onkeydown = function(event) {
if(event.keyCode === 27 || event.keyCode === 13){
window.close();
}
}
如果有人在这里寻找 AngularJS 弹出解决方案
*这不使用 ui-bootstrap 依赖(仅在没有其他方法时推荐)
$scope.openModal = function(index){
$scope.showpopup = true;
event.stopPropagation();//cool part
};
$scope.closeModal = function(){
$scope.cc.modal.showpopup = false;
};
window.onclick = function() {
if ($scope.showpopup) {
$scope.showpopup = false;
// You should let angular know about the update that you have made, so that it can refresh the UI
$scope.$apply();
}
};
//escape key functionality playing with scope variable
document.onkeydown = function (event) {
const key = event.key; // const {key} = event; in ES6+
if (key === "Escape") {
if ($scope.showpopup) {
$scope.showpopup = false;
// You should let angular know about the update that you have made, so that it can refresh the UI
$scope.$apply();
}
}
};
参考文献:上述答案和http://blog.nkn.io/post/hiding-menu-when-clicking-outside---angularjs/
您可以使用Jquery轻松实现绑定按键事件。
.keydown()
$(document).keydown(function(e) {
if (e.keyCode == 27) {
window.close();
}
});
@Gumbo 的答案很好,但通常你需要取消这种行为,所以我建议使用
one
事件处理程序:
$(document).one('keydown', function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
或
$(document).on('keydown', function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
当准备好停止这种行为时
$(document).off('keydown');