如何在击中逃生时关闭模态弹出窗口?

时间:2012-10-10 09:51:35

标签: jquery jquery-ui

我已经制作了一个模态框弹出功能,当有人在所有浏览器中点击转义键时,我想关闭这个模式弹出框。我已将modal-window.min.js文件用于这些弹出窗口。

如何关闭这些以响应此键?

7 个答案:

答案 0 :(得分:18)

$(document).keypress(function(e) { 
    if (e.keyCode === 27) { 
        $("#popdiv").fadeOut(500);
        //or
        window.close();
    } 
});

答案 1 :(得分:11)

使用keydown功能:

$(document).keydown(function(event) { 
  if (event.keyCode == 27) { 
    $('#modal_id').hide();
  }
});
  

注意:首选使用keydown作为Escape键,因为在某些浏览器中,只有在键输出字符时才会触发keypress事件:)

答案 2 :(得分:2)

<script type="text/javascript">
 jQuery(document).keypress(function(e) {
  if (e.keyCode === 27) {
   jQuery("#myModal").modal('toggle');
                 OR
   jQuery("#myModal").modal('hide');
  }
 });
</script>

取自:http://chandreshrana.blogspot.in/2016/05/how-to-close-model-popup-on-escape-key.html

答案 3 :(得分:1)

对于那些正在寻找非jQuery解决方案的人们,这里是:

document.addEventListener('keydown', (event) => {
  if (event.key === 'Escape') {
    // close modal here
  }
})

答案 4 :(得分:0)

尝试此代码:

<script type="text/javascript">
   $(document).keyup(function(event){
      if(event.which=='27'){
          $('.cd-popup').removeClass('is-visible');
      }
   });
</script>

答案 5 :(得分:0)

如果您有多个模态,则可以使用以下脚本。我必须在一页中打开这么多模态,这就是为什么我编写此脚本的原因。该脚本使用转义键根据打开顺序逐个关闭模态。而且您也不需要在脚本中定义任何模式名称,因此可以在任何地方添加一次使用。

var modals=[]; // array to store modal id

$(document).ready(function(){

$('.modal').modal({show: false, keyboard: false}); // disable keyboard because it conflicts below

$('.modal').on('show.bs.modal', function (event) {
   //add modal id to array
   modals.push(event.target.id);
});


document.onkeydown = function(evt) {
    evt = evt || window.event;
    var isEscape = false;
    if ("key" in evt) {
        isEscape = (evt.key === "Escape" || evt.key === "Esc");
    } else {
        isEscape = (evt.keyCode === 27);
    }
    if (isEscape) {

        if(modals.length>0){
            //get last modal id by using pop(). 
            //This function also removes last item in array.
            var id = modals.pop();
            if($('#'+id).is(':visible')){ // if modal is not closed by click or close button
                $('#'+id).modal('toggle');
            }
        }else{
            alert("Could not find any modals!");
        }
    }
};

});

答案 6 :(得分:-1)

使用AngularJs: 如果您有多个模态,

为每个模态分配一个值,当您打开模态时将其设置为true 当你关闭它时,将其设置为false。

//in your .js script

    document.onkeydown = function (event) {
    event = event || window.event;
    if (event.keyCode === 27) {
        if (usersModal)
            $scope.hideUsersModal();
        else if (groupsModal)
            $scope.hideGroupsModal();
    }

使用Angular,event.target属性表示您设置ng控制器的位置,event.currentTarget#document

相关问题