简体   繁体   English

如何使用多个按钮打开单个模式?

[英]How to open single modal with multiple buttons?

I want to make several buttons so that the modal works.我想制作几个按钮以便模态工作。 What should I do?我应该怎么办? And how do I make the background screen fixed when scrolling after modal operation?以及如何在模态操作后滚动时固定背景屏幕?

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal several modal buttons https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal几个模态按钮

<button id="myBtn">Open Modal</button>
<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>
</div>

<button id="myBtn">Open Modal2</button>
<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>
</div>

<button id="myBtn">Open Modal3</button>
<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>
</div>
<script>
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>

Modifying the code, it would look like this修改代码,它看起来像这样
I changed to get the button by class我改为通过 class 获取按钮

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button class="myBtn" >Open Modal</button>
<button class="myBtn" >Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

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

</div>

<script>
// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");
console.log()
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 

for(let i = 0;i < btn.length; i++)
{
 let v = btn[i]
 v.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";
  }
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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