创建一个按钮作为模态的触发器

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

我是 HTML 和 CSS 的初学者,我有一个使用此代码的工作模式系统

<button class="modal-button" href="#myModal1">Open Modal</button>
        <div id="myModal1" class="modal">
          <div class="modal-content">
            <div class="modal-header">
              <span class="close">X</span>
              <h2>Modal Header</h2>
            </div>
            <div class="modal-body">
              <p>Some text in the Modal Body</p>
              <p>Some other text...</p>
            </div>
            <div class="modal-footer">
              <h3>Modal Footer</h3>
            </div>
          </div>
        </div>

这是我的模态脚本

<script>// Get the modal
  // Get the button that opens the modal
var btn = document.querySelectorAll("button.modal-button");

// All page modals
var modals = document.querySelectorAll('.modal');

// Get the <span> element that closes the modal
var spans = document.getElementsByClassName("close");
  
  // When the user clicks on the button, open the modal
  for (var i =0; i<btn.length; i++){
    btn[i].onclick = function(e){
      e.preventDefault();
      modal = document.querySelector(e.target.getAttribute("href"));
      modal.style.display = "block";
    }
  }
  
  // When the user clicks on <span> (x), close the modal
  for(var i = 0; i <spans.length; i++) {
    spans[i].onclick = function(){
      for (var index in modals) {
        if (typeof modals[index].style !== 'undefined') modals[index].style.display = "none";
      }
    }
  }
  
  // When the user clicks anywhere outside of the modal, close it
  window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
      for (var index in modals){
        if (typeof modals[index].style !== 'undefined') modals[index].style.display = "none";
      }
    }
  }</script>

但是我想用这种类型的代码

<button id="connectButton"><img class="icon" src="images/mail.png"><h1>connect</h1></button>
来替换第一行。

我已经尝试过 this 建议的修复,但它对我不起作用。有人能帮忙吗?

javascript html modal-dialog bootstrap-modal
© www.soinside.com 2019 - 2024. All rights reserved.