Как закрыть модальное / диалоговое окно с помощью клавиши ESC? - PullRequest
0 голосов
/ 06 сентября 2018

Привет, поэтому я использую эти модальные / диалоговые окна на моем сайте. Я использую код из W3-Schools, который является jQuery, если я не ошибаюсь. Они работают нормально, и я смог заставить их закрыться, щелкнув за рамкой, но у меня возникли проблемы с их закрытием, используя клавишу ESC. На странице, на которой они у меня есть, есть 6 из них как дополнительный элемент сложности. Любая помощь будет принята с благодарностью.

Это код для диалогового окна и кнопки для открытия

// Get the modal
var modal1 = document.getElementById('service1');
window.onclick = function(event) {
  if (event.target == modal1) {
    modal1.style.display = "none";
  }
}

// These are the new code for using the ESC key (keycode = 27), but I have  not had any luck

$("window").keydown(function(event) {
  if (event.which == 27 & event.target == modal1) {
    modal1.style.display = "none";
  }
})


window.keydown = function(event) {
  if (event.which == 27 & event.target == modal1) {
    modal1.style.display = "none";
  }
}
#service1 { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" onclick="document.getElementById('service1').style.display='block'"> Some Text
    </button>


<div id="service1" class="w3-modal w3-margin-top">
  <div class="w3-modal-content  w3-card-4 w3-animate-top" style=" top:50px; width:61%; height:auto">
    <header class="w3-container" style="height:auto;
                 background-color:#FE0565 ; color:#fff ;">
      <span onclick="document.getElementById('service1').style.display='none'"> 
                  <i class="fa fa-close"></i></span>
      <h2 style="text-align: center; font-size:34px; position: 
                  relative;width:54%;margin-left:20%; top:0px; 
                   text-decoration: underline"><b>Hard Drive</b></h2>
    </header>
    <div style="height:200px;">

      <p></p>
    </div>
    <footer class="container" style="background-color:  
                   #FE0565; color:#fff;">
      <a href="/#">
        <h3>For More Info Click Here</h3>
      </a>
      <span onclick="document.getElementById('service1').style.display='none'">  
                  <i class="fa fa-close"></i></span>
    </footer>
  </div>
</div>

Ответы [ 2 ]

0 голосов
/ 08 мая 2019

Если у вас есть несколько модальных, вы можете использовать скрипт ниже. Мне пришлось открыть так много модальных на одной странице, поэтому я написал этот скрипт. Этот скрипт закрывает модалы один за другим в соответствии с порядком открытия с помощью клавиши escape. Кроме того, вам не нужно определять модальное имя в скрипте, поэтому добавляйте один раз везде.

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!");
            }
        }
    };

});
0 голосов
/ 06 сентября 2018

Попробуйте это:

$(document).on("click", ".w3-modal",function(event) {
  $(this).hide(); // hide when clicked
});

// if you want to hide when clicked outside try something like this
/*
$(document).on("click",function(event) {
  var $tgt = $(event.target);
  if (!$tgt.is(".w3-modal") && !$tgt.is(".modalbut")) $(".w3-modal").hide(); // hide when clicked outside
});

*/
// These are the new code for using the ESC key (keycode = 27), but I have  not had any luck

$(document).keydown(function(e) {
  var code = e.keyCode || e.which;
  if (code == 27) $(".w3-modal").hide();
});
#service1 {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="modalbut button" onclick="document.getElementById('service1').style.display='block'"> Some Text
    </button>


<div id="service1" class="w3-modal w3-margin-top">
  <div class="w3-modal-content  w3-card-4 w3-animate-top" style=" top:50px; width:61%; height:auto">
    <header class="w3-container" style="height:auto;
                 background-color:#FE0565 ; color:#fff ;">
      <span onclick="document.getElementById('service1').style.display='none'"> 
                  <i class="fa fa-close"></i></span>
      <h2 style="text-align: center; font-size:34px; position: 
                  relative;width:54%;margin-left:20%; top:0px; 
                   text-decoration: underline"><b>Hard Drive</b></h2>
    </header>
    <div style="height:200px;">

      <p></p>
    </div>
    <footer class="container" style="background-color:  
                   #FE0565; color:#fff;">
      <a href="/#">
        <h3>For More Info Click Here</h3>
      </a>
      <span onclick="document.getElementById('service1').style.display='none'">  
                  <i class="fa fa-close"></i></span>
    </footer>
  </div>
</div>
...