多次使用ID打开弹框

问题描述 投票:0回答:1

我已经使用这个教程构建了一个带有联系表单的弹出框,但是我想在多个地方使用它,而无需复制代码并更改每个按钮的ID

如果您需要更多信息,请告诉我任何建议,我将编辑问题

这是我的网站,我已将 id 添加到两个滑块链接

这是我的弹出框和按钮

 <button id="myBtn" class="btn btn-light">
   click here
  </button>
    
    <div id="myModal" class="modal">
    
      <!-- Modal content -->
      <div class="modal-content">
        <span class="close">&times;</span>
        <?php echo do_shortcode('[wpforms id="439"]'); ?>
      </div>

这是我的javascript

// 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";
  }
}
javascript jquery css popup
1个回答
0
投票

在这里您可以找到运行良好的多种模式。

// Get the modal
function openModal(modal)
{
  var modal = document.getElementById(modal);
    modal.style.display = "block";
    var span = document.querySelector("#"+modal.id+" .close");
    span.onclick = function() {
      modal.style.display = "none";
    }
    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }
}
body {font-family: Arial, Helvetica, sans-serif;}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  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.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

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

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button onclick="openModal('modal1')">Open Modal 1</button>
<button onclick="openModal('modal2')">Open Modal 2</button>

<!-- The Modal 1 -->
<div id="modal1" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal1..</p>
  </div>
</div>

<!-- The Modal 2 -->
<div id="modal2" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal2..</p>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.