JavaScript在同一点击中隐藏点击外部触发两次

时间:2018-04-14 14:44:15

标签: javascript

我有这段代码:

完整代码: https://codepen.io/anon/pen/wmLBxW

JavaScript代码:

function HideOnClickOutside(aContentElement, aFullScreenElement) {
  const outsideClickListener = event => {
    event.preventDefault();
    let isClickInside = aContentElement.contains(event.target);
    if (!isClickInside) {
      aFullScreenElement.classList.toggle("hidden", true);
      removeClickListener();
    }
  };

  const removeClickListener = () => {
    document.removeEventListener("click", outsideClickListener);
  };

  document.addEventListener("click", outsideClickListener);
}

CSS

  #fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: auto;
  background: black;
  opacity: 0.5;
}

.hidden {
  display: none;
}

#journal-show-entry {
  display: flex;
  justify-content: center;
  width: 40%;
  height: 60%;
  border: 1px solid #9b6400;
  background-color: #ffffff;
}

HTML

<a href="#" onclick="ShowFullScreenDiv()">Link</a>

<div id="fullscreen" class="hidden">
  <div id="journal-show-entry">
  </div>
</div>

我在这个帖子中找到了: How do I detect a click outside an element?

然而就像在我的CodePen中一样,它会在同一个点击上触发outsideClickListener,它会添加EventListener,使div在同一个点击上再次隐藏,因此永远不会显示。

为什么会这样?

1 个答案:

答案 0 :(得分:1)

发生的事情是事件传播到下一层(隐藏的div)

添加此项将解决您的问题:

function ShowFullScreenDiv(event) {
  event.stopPropagation(); // <-- add this
  divFullScreen.classList.toggle("hidden", false);
  HideOnClickOutside(divEntry, divFullScreen);
}

并且当然将事件添加到html:

<a href="#" onclick="ShowFullScreenDiv(event)">Link</a>