首页 > 解决方案 > 如果检查 CSS 属性的语句不起作用

问题描述

我有一个 div,单击时会显示一个小弹出菜单。我希望用户能够单击网站正文中的任意位置来关闭弹出窗口,但是当我为此添加代码时,弹出窗口根本无法打开。

因此,我尝试添加一个 if 语句,以便 closemenu() 函数仅在弹出窗口已打开时才尝试关闭它,但即使弹出窗口已打开,该语句的评估结果似乎也为 false。

这是显示弹出窗口的 HTML:

    <div class="popcolor" onclick="showmenu()"> Click!
        <span class="popupcolor" id="myPopup">Pop!</span>
    </div>

这是CSS:

    .popcolor .show {
        visibility: visible;
        -webkit-animation: fadeIn 0.5s;
        animation: fadeIn 0.5s;
    }

这是Javascript:

function showmenu() {
    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}

function closemenu() {
    var popup = document.getElementById("myPopup");
    if (popup.style.visibility == "visible") {
        popup.classList.toggle("close");
    };
}

这是关闭弹出窗口的 HTML:

<body onclick="closemenu()">

我已经浏览了所有我能找到的关于解决方案的帖子,但我仍然被困住了。任何帮助表示赞赏。

标签: javascripthtmlcss

解决方案


您可以使用对象getComputedStyle()上的方法window来计算应用到popup元素的类所产生的样式规则。

这为您提供了一种可靠的方法来确定不同样式规则的值,例如,应用到的“关闭”类popup

类似的东西应该适合你:

function closemenu() {

    var popup = document.getElementById("myPopup");

    // Get the computed style, that is the combination of styles 
    // resulting from your CSS classlist, etc
    var computedStyle = window.getComputedStyle(popup, null); 

    // Get visibility value from computed styles
    var visiblityValue = computedStyle.getPropertyValue("visibility")

    if (visiblityValue == "visible") {
        popup.classList.toggle("show"); // Correct this from "close" to "show"
    };
}

您的实现还有一些其他功能问题会导致问题。考虑将您的showmenu()方法更新为:

function showmenu(event) {

    // Prevent event propagation, which would cause closemenu to call 
    // after this method is called
    event.stopPropagation()

    var popup = document.getElementById("myPopup");
    popup.classList.toggle("show");
}

有关 的更多信息getComputedStyle()请参阅 MDN 文档


推荐阅读