JS Modal-不使用Bootstrap

时间:2018-03-16 00:25:56

标签: javascript jquery html css

如何使用锚标记而不是按钮来触发模态?我无法使用Bootstrap,因为我需要修改模态的大小。我尝试将ID放入href,但这并没有帮助。有什么建议?



// 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 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";
    }
}
&#13;
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

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

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
     
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

如果您只是将现有的<button>代码更改为<a>,那么您现有的JS代码应该可以运行。原理完全相同,通过ID获取元素的引用,然后附加一个单击处理程序。

但是为了让锚点显示为链接它需要一个href,所以我使用了href="#",然后更新了click函数以取消默认的点击行为。

你可能也想要一些CSS最初隐藏模态。

// 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 the button, open the modal 
btn.onclick = function(e) {
    e.preventDefault();  // ADDED this line
    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";
    }
}
#myModal { display: none; }  /* added this CSS */
<!-- Trigger/Open The Modal -->
<a id="myBtn" href="#">Open Modal</a>  <!-- changed tags, added href, kept id -->

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

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
     
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>