为什么我的模式关闭按钮不起作用?

时间:2018-12-05 20:00:43

标签: javascript

我“制作”了一个模态(从here获得了)。但是,关闭模态的按钮不起作用。单击该模式的任何部分以关闭它的事件确实起作用。我已经花了几个小时并进行了尽可能多的研究,但似乎还是找不到问题。

const modal = document.querySelector(".modal");
const closeModal = document.querySelector(".closeModal");

document.querySelector("#shortCircuit").onclick = function() {
  modal.setAttribute('style', 'display: block;');
}

closeModal.onclick = function() {
  modal.setAttribute('style', 'display: none;');
}

window.onclick = function(event) {
  if (event.target === modal) {
    modal.setAttribute('style', 'display: none;');
  }
}
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: hsl(0, 0%, 0%);
  background-color: hsla(0, 0%, 0%, 0.4);
}

.modal-content {
  background-color: hsl(0, 0%, 100%);
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #878787;
  width: 80%;
}

.closeModal {
  color: #aaa;
  float: right;
  font-size: 2em;
  font-weight: bold;
}

.closeModal:hover,
.closeModal:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
<div class="flexLayout">
  <div id="shortCircuit">
    <h1>Short-circuit</h1>
    <div class="modal">
      <div class="modal-content">
        <button class="closeModal">&times;</button>
      </div>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:4)

问题是您单击X会使DOM冒泡,并再次在<div id="shortCircuit">上触发打开的模式代码。您可以使用e.stopPropagation();

停止

const modal = document.querySelector(".modal");
const closeModal = document.querySelector(".closeModal");

document.querySelector("#shortCircuit").onclick = function() {
  modal.setAttribute('style', 'display: block;');
}

closeModal.onclick = function(e) {
  e.stopPropagation();
  modal.setAttribute('style', 'display: none;');
}

window.onclick = function(event) {
  if (event.target === modal) {
    modal.setAttribute('style', 'display: none;');
  }
}
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: hsl(0, 0%, 0%);
  background-color: hsla(0, 0%, 0%, 0.4);
}

.modal-content {
  background-color: hsl(0, 0%, 100%);
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #878787;
  width: 80%;
}

.closeModal {
  color: #aaa;
  float: right;
  font-size: 2em;
  font-weight: bold;
}

.closeModal:hover,
.closeModal:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
<div class="flexLayout">
  <div id="shortCircuit">
    <h1>Short-circuit</h1>
    <div class="modal">
      <div class="modal-content">
        <button class="closeModal">&times;</button>
      </div>
    </div>
  </div>
</div>

答案 1 :(得分:0)

该代码的问题是它正在关闭对话框,然后触发显示对话框事件。这是因为单击事件在鼠标下方的每个层中冒泡。要停止此操作,只需将代码更改为此

closeModal.onclick = function(e) {
  modal.setAttribute('style', 'display: none;');
    e.preventDefault();
    e.stopPropagation();
}