在容器外部单击时,模态停止工作

时间:2019-03-04 03:48:28

标签: javascript

模态已经在工作,单击按钮打开模态,单击x按钮关闭模态,但是,我尝试添加
const mainWrapper = document.querySelector(".modal-main-wrapper");和逻辑。

我添加它的原因是因为当我单击“容器或模态外部”时,它会关闭,但看来我的模态停止工作。

那它怎么了?我也尝试将其定位为身体,
const closeBody = document.querySelector("body");,但仍然无法正常工作。

const buttonClick = document.querySelector(".button-click");
const modalWrapper = document.querySelector(".modal-wrapper");

buttonClick.addEventListener("click", _ => {
  modalWrapper.classList.add("modal-show");
})

const buttonClose = document.querySelector(".modal-button-close");

buttonClose.addEventListener("click", _ => {
  modalWrapper.classList.remove("modal-show");
})

//The problem starts from here
const mainWrapper = document.querySelector(".modal-main-wrapper");

mainWrapper.addEventListener("click", _ => {
  modalWrapper.classList.remove("modal-show");
})
.button-click {
  padding: 10px 15px;
  border-radius: 5px;
  font-size: 40px;
  color: #ffffff;
}

.modal-wrapper {
  visibility: hidden;
}

.modal-wrapper.modal-show {
  visibility: visible;
}
<body>
  <div class="modal-main-wrapper">
    <button class="button-click">Click me!</button>

    <div class="modal-wrapper">
      <button class="modal-button-close">x</button>
      <p>Hello</p>
    </div>
  </div>
</body>

1 个答案:

答案 0 :(得分:1)

当您单击按钮时,它还会触发对父级modal-main-wrapper的单击。为防止这种情况,您应该使用Event.stopPropagation()

  

stopPropagation():事件接口的方法防止在捕获和冒泡阶段进一步传播当前事件

const buttonClick = document.querySelector(".button-click");
const modalWrapper = document.querySelector(".modal-wrapper");

buttonClick.addEventListener("mousedown", _ => {
  console.log("clicked")
  modalWrapper.classList.add("modal-show");
  console.log(modalWrapper.outerHTML)
  _.stopPropagation()
})

const buttonClose = document.querySelector(".modal-button-close");

buttonClose.addEventListener("click", _ => {
  modalWrapper.classList.remove("modal-show");
  _.stopPropagation(); 
})

//The problem starts from here
const mainWrapper = document.querySelector(".modal-main-wrapper");

mainWrapper.addEventListener("mousedown", _ => {
  console.log('clicked');
  modalWrapper.classList.remove("modal-show");
})
.button-click {
  padding: 10px 15px;
  border-radius: 5px;
  font-size: 40px;
  color: #ffffff;
}

.modal-wrapper {
  visibility: hidden;
}
.modal-show {
  visibility: visible !important;
}
<body>
  <div class="modal-main-wrapper">
    <button class="button-click">Click me!</button>

    <div class="modal-wrapper">
      <button class="modal-button-close">x</button>
      <p>Hello</p>
    </div>
  </div>
</body>