Javascript模式需要两次点击才能打开

时间:2016-11-30 19:04:31

标签: javascript html css css3 modal-dialog

单击按钮后代码应该打开一个模态窗口,但是当你第一次打开它时,需要两次点击按钮才能打开它。 从W3Schools复制一些代码并修改它以使其适合我的JS文件后,我遇到了这个问题。

HTML

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn" onclick="modalFunction()">Open Modal</button>

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

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

</div>

Javasript

function modalFunction() {
// 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";
    }
}
}

1 个答案:

答案 0 :(得分:2)

如果将事件加载处理程序移到函数之外,它将按预期工作。

这里我只删除了函数和内联脚本处理程序。

请注意,脚本需要在页面加载时运行,而不是在

之前运行

&#13;
&#13;
window.addEventListener('load', function() {

  // 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;
.modal {
  display: none
}
&#13;
<h2>Modal Example</h2>

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

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

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

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

相关问题