如何处理 javascript 弹出窗口上的 ESC 键按下

问题描述 投票:0回答:8

我有一个 javascript window.open 弹出窗口,我希望当用户按 ESC 键时弹出窗口自行关闭。我不知道如何挂钩 keydown 事件(以及在什么对象上?)以便我可以捕获 ESC 键。

我正在使用 jQuery。

javascript jquery popup
8个回答
121
投票

尝试这样的事情:

$(document).keydown(function(e) {
    // ESCAPE key pressed
    if (e.keyCode == 27) {
        window.close();
    }
});

74
投票

不用jQuery,用JS就可以实现。

window.onkeydown = function( event ) {
    if ( event.keyCode == 27 ) {
        console.log( 'escape pressed' );
    }
};

31
投票

event.key ===“逃脱”

不再有任意数字代码!

document.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; in ES6+
    if (key === "Escape") {
        window.close();
    }
});

Mozilla 文档

支持的浏览器


4
投票

请记住,您必须在弹出窗口中使用函数@Gumbo posts...因此您需要在弹出窗口中包含 JQuery 并在那里执行该函数,而不是打开弹出窗口的窗口。


4
投票

处理对话框中的 esc 和 Enter 键

window.onkeydown = function(event) {
    if(event.keyCode === 27 || event.keyCode === 13){
       window.close();
    }
}

1
投票

如果有人在这里寻找 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/


0
投票

您可以使用Jquery轻松实现绑定按键事件

在这里您可以使用

.keydown()

键盘按键代码列表

  $(document).keydown(function(e) {        
    if (e.keyCode == 27) {
        window.close();
    }
});

0
投票

@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');
© www.soinside.com 2019 - 2024. All rights reserved.