javascript - 如果检查 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()">
我已经浏览了所有我能找到的关于解决方案的帖子,但我仍然被困住了。任何帮助表示赞赏。
解决方案
您可以使用对象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 文档
推荐阅读
- sql - SQL:查询带有每日标志表的单日期表
- python - WFDB Plot-Demo 导致 TypeError
- node.js - 根域中的 Index.html 没有在角度 IIS 中获得服务器端渲染
- raspberry-pi - 为什么用杯子打印pdf在树莓派上很慢,比如30秒后开始
- php - Route::get 带参数和重定向
- python - 为什么我在导入时不必指定子模块?
- c# - C# selenium 找不到元素
- angular - 如何在Angular6中使用forkJoin和ngrx进行多个HTTP调用?
- amazon-web-services - AWS Lambda 函数抛出读取超时。(读取超时=60)调用时
- java - Java web start 应用程序不会触发事件