Creating Multiple Modals on a Single Page

前端 未结 4 854
南笙
南笙 2020-12-15 14:35

I\'m having some issues creating multiple modals on a single webpage following the sample code from w3schools.com. The code in question that I am using is this one: http://w

4条回答
  •  感动是毒
    2020-12-15 15:31

    On your JSFiddle, make sure you use class="myBtn" instead of id="myBtn" then it should work.

    Here is the full working code:

    HTML:

    1st Modal

    2nd Modal

    JS:

    // Get the modal
    var modal = document.getElementsByClassName('modal');
    
    // Get the button that opens the modal
    var btn = document.getElementsByClassName("myBtn");
    
    
    // Get the  element that closes the modal
    var span = document.getElementsByClassName("close");
    
    // When the user clicks the button, open the modal 
    btn[0].onclick = function() {
        modal[0].style.display = "block";
    }
    
    btn[1].onclick = function() {
        modal[1].style.display = "block";
    }
    // When the user clicks on  (x), close the modal
    span[0].onclick = function() {
        modal[0].style.display = "none";
    }
    
    span[1].onclick = function() {
        modal[1].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";
        }
    }
    

提交回复
热议问题