Как я могу закрыть мой модальный ящик в Bootstrap? - PullRequest
0 голосов
/ 03 июля 2019

У меня есть модальное окно, которое я могу назвать хорошо, но я не могу закрыть его, независимо от того, нажимаете ли вы на x или где-нибудь еще на экране.Извините, если я недостаточно хорошо это описываю - я очень новичок.

Я попробовал демо-версию школы w3, а также другие примеры, и просто не могу понять, что я делаю неправильно.Полный код, указанный ниже по запросу.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Benny the virtual blob</title>
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="virtualpet.css">
    <link href="https://fonts.googleapis.com/css?family=Barriecito|Special+Elite&display=swap" rel="stylesheet">
    <script src="https://kit.fontawesome.com/de2b0ad954.js"></script>
</head>
<body>
  <div id="myModal" class="modal">
                    <div class="modal-content">
                        <span class="close">&times;</span>
                          <i class="fas fa-skull-crossbones"></i><br>
                            <p>"Oh, no! You killed Benny!"<br>
                               "He was <span id="dead">x</span> days young"</p>
                              </div>
                            </div>
  <div class="container">
    <h1>Benny the Blob</h1>

      <p>Look after Benny, the blob. Play with him, feed him, care for him when he's sick. But if you ignore him for too long, he'll die. How long will you be able to keep him alive?</p>

        <button type="button" class="btn reset">Birth Benny</button>

  </div>

  <div class="action">
     <img id="age" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857600/virtual%20pet/item-box.png" alt="window for life span">
        <img id="backing" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561670551/virtual%20pet/little-board.png" alt="pin board image">
           <div id="bennyNormal" class="start"></div>
               <p id="ageStatus" class="start" ><span id="days">0</span> days old</p>
                  <img id="heart" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561725918/virtual%20pet/l1.png"  alt="health points image">
                      <img id="star" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s1.png" alt="happy points image">

                         <img id="hungry" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h1.png" alt="hunger points image"> 


                              <div id="tasks">
                                   <img id="medicine" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857719/virtual%20pet/medicene.png" alt="medicine">
                                       <img id="food" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857661/virtual%20pet/sandwich.png" alt="food">
                                          <img id="toys" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857776/virtual%20pet/gamesbox.png" alt="toys">
                                                <img id="drink" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857689/virtual%20pet/red-smoothie.png" alt="glass of juice"> 

                              </div>





</div>







<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="virtualpet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>



</body>
</html>
var resetBtn = document.querySelector(".reset");
var start = document.querySelectorAll(".start");
var ageing = document.getElementById("days");
var heart= document.getElementById("heart");
var star = document.getElementById("star");
var tummy = document.getElementById("hungry");
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
var content = document.getElementsByClassName("modal-content")
var dead = document.getElementById("dead");


$(document).ready(function () {


var count=0;
var c = count;
var cd = $('#days');

$(resetBtn).click(function(){
    $(".start").toggle();
     if ($(this).text() == "Birth Benny") { 
        $(this).text("Restart"); 
    } else { 
        $(this).text("Birth Benny"); 
    }});


    var interv = setInterval(function() {
        c++;
        cd.html(c);
      randomNum();
      happyStatus();
      hungerStatus();
      healthStatus();
    }, 60000);

















var health = 4;
var happy = 4;
var hungry = 4;

function randomNum(){

//pick a 'health' 
  var h=Math.random();
  //pick a happy 
  var s=Math.random();
  //pick a hungry
  var f=Math.random();

  if (h <0.5) {
    health--;
  }
  if (s <0.5) {
    happy--;
  }

  if (f <0.5) {
    hungry--;
  }
 };

function healthStatus(){
if (health===4){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725918/virtual%20pet/l1.png");
}if(health===3){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l2.png");
}if (health===2){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l3.png");
}if(health===1){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l4.png");
}if (health===0){
  deathScreen();
}
};

function happyStatus(){
if (happy===4){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s1.png");
}if(happy===3){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s2.png");
}if (happy===2){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s3.png");
}if(happy===1){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s4.png");
}if (happy===0){
  deathScreen();
}
};

function hungerStatus(){
if (hungry===4){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h1.png");
}if(hungry===3){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h2.png");
}if (hungry===2){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h3.png");
}if(hungry===1){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h4.png");
}if (hungry===0){
  deathScreen();
}
};



function deathScreen(){

$(start).hide();
$('#myModal').modal('show');
$(dead).text(c);
clearInterval(interv);
};


$(span).on("click", function(){
$('#myModal').modal('toggle');
});

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    $('#myModal').modal('toggle');
  }
}




});
body {
  margin: 0;
  text-align: center;
}
h1 {
  font-family: 'Barriecito', cursive;
  text-align: center;
}

p {
  font-family: 'Special Elite', cursive;
  text-align: left;
}

#ageStatus {
  top: -850px;
  left: 150px;
  position: relative;
  font-size: 2em;
  display: none;
}

.container {
  width: 600px;
  margin: 0 auto;
  text-align: center;
}

.btn{
  background-color: pink!important;
  font-family: 'Barriecito', cursive;
}

#backing {
  width: 800px;
  margin: 0 auto;
  z-index: -10;
  position: relative;
  top: 0px;
  display: none;

}

#bennyNormal {
  width:327px;
  height: 444px;
  display: none;
  background-image:url("https://res.cloudinary.com/dytmcam8b/image/upload/v1561677299/virtual%20pet/Sheet.png");
  top: -450px;
  left:250px;
  position: relative;
  transform: scale(0.5);
  -webkit-animation: benny 3s steps(10) infinite;
       -moz-animation: benny 1.5s steps(10) infinite;
        -ms-animation: benny 1.5s steps(10) infinite;
         -o-animation: benny 1.5s steps(10) infinite;
            animation: benny 1.5s steps(10) infinite;
}
   @-webkit-keyframes benny{
    from{background-position:0px;}
to{background-position:-3270px;}
}
  }

  @keyframes normal{
    from {background-position:0px;}
to {background-position:-3270px;}
}


  #heart {
    height: 150px;
    width: 150px;
    transform: scale(0.5);
    top: -970px;
    left: 400px;
    position: relative;
    display: none;
    }
 #star {
    height: 150px;
    width: 150px;
   top: -970px;
   left: 350px;
    transform: scale(0.5);
    position: relative;
   display: none;
}


 #hungry {
    height: 80px;
    width: 80px;
    position: relative;
    left: 330px;
   top: -970px;
   display: none;
    }

#age {
  width: 250px;
  position: relative;
  top: 180px;
  left: 100px;
  display: none;
}

#medicine {
  width: 100px;
  position: relative;
  top: -870px;
  left: 150px;
  display: none;
   }

#toys {
  width: 100px;
  position: relative;
  top:-1000px;
  left:-50px;
  display: none;
  }

.action {
  position: relative;
  height: 400px;
  width: 800px;
  margin: 0 auto;
}

#food {
  width: 100px;
  position: relative;
  left: 440px;
  top: -1000px;
  display: none;
   }

#drink{
  width: 100px;
  position: relative;
  left: 240px;
  top: -900px;
  display: none;
  }

.hidden {
  display: block;
}

.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 100; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(242, 114, 223); /* Fallback color */
  background-color: rgb(242, 114, 223); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid rgb(242, 114, 223);
  width: 20%; 
  font-family: 'Barriecito', cursive;
  font-size: 2em;
  text-align: center;

}

/* The Close Button */
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

#dead {
  text-align: center;
}

Мой x не отвечает, и я не могу щелкнуть где-нибудь еще на экране, чтобы закрыть его.В Chrome нет сообщений об ошибках.Когда я наведу курсор на x, ссылка появляется как «мертвая».

Ответы [ 4 ]

1 голос
/ 03 июля 2019

Используйте .modal('toggle') в соответствии с документами здесь: https://getbootstrap.com/docs/4.0/components/modal/#modaltoggle

$('#myModal').modal('toggle');

Но в модальном поведении по умолчанию, когда пользователь щелкает модальное окно (серая область), оно автоматически закрывается, вот как это работает: https://jsfiddle.net/Lc8ayf9k/

Рассмотрите обзор ссылок javascript и stylesheet на своей странице

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
0 голосов
/ 03 июля 2019

Я считаю, что то, как вы подключили слушателей событий, неверно. Если вы используете vanilla javascript, вы должны сначала назначить DOM внутри переменной:

var thisSpan = document.getElementById("close");
thisSpan.addEventListener("click", function(){
    modal.style.display = "none";
});

С jQuery это немного проще, особенно если вы используете загрузочный модальный плагин. Вы можете следовать другим решениям, данным коллегами здесь. Если это пользовательский модал, то мы можем иметь шаблон, аналогичный предыдущему коду:

$("#close").on("click", function(){
    modal.style.display = "none";
});
0 голосов
/ 03 июля 2019

Если вы используете Bootstrap, то файл модальных настроек bootstrap.js должен иметь возможность закрыть модальный режим. Вот пример модального Bootstrap.

`<div id="myModal" class="modal fade" role='dialog'>
   <div class="modal-dialog">
     <div class="modal-content">
       <div class="modal-header">
         <h4>myModal</h4>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close" title="Close">
              <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
           <p>"Oh, no! You killed Benny!"<br>
           "He was <span id="dead">x</span> days young"</p>
        </div>
      </div>
     </div>
   </div>`

Если вам нужен пользовательский JavaScript для закрытия модального режима, вы можете попробовать этот скрипт:

`<script type="text/javascript">
   // Get the modal object
   var modal = document.getElementById('myModal');

  // Get the <span> element that closes the modal
  var span = document.getElementsByClassName("close")[0];

  // When the user clicks on <span> (x), close the modal
  span.onclick = function() {
      modal.style.display = "none";
    }

  // When the user clicks anywhere outside of the modal, close it
  window.onclick = function(event) {
     if (event.target == modal) {
       modal.style.display = "none";
       }
    }
   </script>`
0 голосов
/ 03 июля 2019

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

$('#myModal').modal('toggle');
...