一个页面上有多个模态框

More than one Modal Boxes on one page

本文关键字:模态 一个      更新时间:2023-09-26

这里我放了两个按钮,点击它们会弹出一个模式框。

 <li type="button" id="myBtn" class="w3-hide-small w3-center"><a href="#" class="w3-hover-white">1</a></li>
 <li type="button" id="myBtn2" class="w3-hide-small w3-center"><a href="#" class="w3-hover-white">2</a></li> 

这是第一周的模态信息:

<!-- MODAL INFORMATION FOR WEEK 1  -->
<div id="myModal" class="modal">
  <div class="modal-content">
      <span class="close">×</span>
    <p><h2><font color="black">Week 1</font></h2></p>
    <div class="modal-body">
      <p><font color="black"> ex1</p>
    </div>
  </div>
</div>

这是第二周的模态信息:

<div id="myModal2" class="modal">
  <div class="modal-content">
      <span class="close">×</span>
    <p><h2><font color="black">Week 2</font></h2></p>
      <p><font color="black"> Example 1 </p>
  </div>
</div>

脚本:

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

我认为改变ID将允许我以不同的方式对待模态框彼此,我也叫"Btn"answers"Btn2"不同。

当我点击1和2时,它们都打开了第1周和第2周的相同文本

你看到相同内容的原因是因为你的目标是相同的模态:

btn.onclick = function() {
    modal.style.display = "block";
}
btn2.onclick = function() {
    modal.style.display = "block"; <--- should be modal2
}

尝试为模态添加data属性。你需要相同的id在你的模态与相同的data-target按钮

交货

<!-- MODAL INFORMATION FOR WEEK 1  -->
<div id="myModalA" class="modal">
  <div class="modal-content">
      <span class="close">×</span>
    <p><h2><font color="black">Week 1</font></h2></p>
    <div class="modal-body">
      <p><font color="black"> ex1</p>
    </div>
  </div>
</div>

<div id="myModal2" class="modal">
  <div class="modal-content">
      <span class="close">×</span>
    <p><h2><font color="black">Week 2</font></h2></p>
      <p><font color="black"> Example 1 </p>
  </div>
</div>

 <li type="button" id="myBtn" class="w3-hide-small w3-center" data-target="myModalA"><a href="#" class="w3-hover-white">1</a></li>

 <li type="button" id="myBtn2" class="w3-hide-small w3-center" data-target="myModal2"><a href="#" class="w3-hover-white">2</a></li>