简体   繁体   中英

how to make multi modal ( with pure css) to target unique id?

I have multi galleries with different gallery sets but the problem is how to target with existing code right one on event

Here is my current js that work on single modal

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

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

// When the user clicks on the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// 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";
    }
}
/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

here is html code that open via ID; what i need is to have like data-target="model-01" and then model-02 to know what need to be open

 <a id="myBtn" href="javascript:void();">
 <!-- The Modal -->
        <div id="myModal" class="modal">
            <!-- Modal content -->
            <div class="modal-content">
                <span class="close">&times;</span>
                <?php
                    include_once("gallery/gallery_modal.php");
                ?>
            </div>
        </div>```

You can add same class "open-modal" and unique data-target attribute to all buttons

<a id="myBtn" class="open-modal" data-target="myModal<?=$r['id'];?>" href="#">Button</a>

<span class="close" data-target="myModal<?=$r['id'];?>">&times;</span>

Than in js

$('.open-modal').on('click', function(){
   event.preventDefault();
   var modal = $('#' + $(this).data('target'));

   modal.css('display', 'block');
});

$('.close').on('click', function(){
   var modal = $('#' + $(this).data('target'));

   modal.css('display', 'none');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM