簡體   English   中英

如何在 javascript 彈出窗口上處理 ESC keydown

[英]How to handle ESC keydown on javascript popup window

我有一個 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' );
    }
};

event.key === "Escape"

沒有更多的任意數字代碼!

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

Mozilla 文檔

支持的瀏覽器

請記住,您必須使用在彈出窗口中發布@Gumbo函數...因此您需要在彈出窗口中包含 JQuery 並在那里執行該函數,而不是打開彈出窗口的窗口。

要同時處理 esc 和在對話框中輸入鍵 window.onkeydown = function(event) {

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

您可以使用 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');

如果有任何尋找 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM