尽管关闭,弹出窗口仍保留在占领区中

时间:2020-06-03 02:03:31

标签: javascript

我遇到以下问题:我做了一个弹出窗口的简单实现,但是当我将其关闭并将光标放在以前是弹出窗口的空白区域时,我现在可以单击此处(在空白区域),然后单击弹出窗口再次出现。也就是说,它似乎没有关闭,而是保留在它先前占用的区域中。可以请某人帮助我,因为我不知道如何永久关闭它。

function fPopUp() {
  var PopUp = document.getElementById("IDPopUp");
  PopUp.classList.toggle("show");
}
/* Popup container - can be anything you want */
.popup {
    position: absolute;
    /*display: block;*/
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* The actual popup */
.popup .popuptext {
    visibility: hidden;
    /*display: none;*/
    width: 500px;
    background-color: grey;
    color: #fff;
    text-align: left;
    border-radius: 6px;
    padding: 8px 0;
    z-index: 1;
    bottom: 125%;
    left: 50%;
}

/* Popup arrow */
.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
    visibility: visible;
    -webkit-animation: fadeIn 1s;
    animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
    from {opacity: 0;} 
    to {opacity: 1;}
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
}
<button id="bAbout" onclick="fPopUp()">PopUp</button>

<div class="popup" onclick="fPopUp()">
  <span class="popuptext" id="IDPopUp">"some text"</span>
</div>

1 个答案:

答案 0 :(得分:2)

使用visibility: hidden将元素隐藏起来,但该元素仍将占据其在文档中的预定空间。要完全隐藏元素,您需要使用display: none,但这在动画中效果不佳。

您的代码使事情变得复杂得多,所以请允许我进行一些修改。这里有一些建议:

  1. id放置在实际弹出窗口中,而不是其内容。您正在尝试显示/隐藏弹出窗口,而不是文本。
  2. 这是一个非常简单的动画,因此简单的CSS过渡就可以了。
  3. 使用pointer-events: none使您的元素对鼠标事件无响应。该元素仍然会占用其通常的空间,但没人会知道。

function fPopUp() {
  IDPopUp.classList.toggle("show");
}
/* Popup container - can be anything you want */
.popup {
    position: absolute;
    cursor: pointer;
    user-select: none;
    pointer-events: none;
    opacity: 0;
    transition: opacity 1s;
}

/* The actual popup */
.popup .popuptext {
    width: 500px;
    background-color: grey;
    color: #fff;
    text-align: left;
    border-radius: 6px;
    padding: 8px 0;
    z-index: 1;
    bottom: 125%;
    left: 50%;
}

/* Popup arrow */
.popup .popuptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup.show {
    opacity: 1;
    pointer-events: auto;
}
<button id = "bAbout" onclick = "fPopUp()">PopUp</button>

<div id = "IDPopUp" class = "popup" onclick = "fPopUp()">
  <span class = "popuptext">"some text"</span>
</div>