使用元素的样式属性作为 if 或 for 循环 javascript 中的条件

2024-03-19

我在理解 If 语句 [或 For lopp] 中的条件时遇到问题。我创建了像菜单按钮一样的 div。当我单击该 div 时,会显示包括此菜单按钮在内的所有菜单,而且文本 [div 内的段落] 也会更改为“关闭菜单”。我试图在单击“菜单”按钮时启动的函数中创建一些 if 条件,但看起来 if 条件无法像我想要的那样工作。下面是一个 for 循环的例子:

function Show_mobile_menu() {
for (;  document.getElementById("Menu_button").style.cssText ="align-self:flex-end;" ; ) {
Func1(); }
}
for (; document.getElementById("Menu_button").style.cssText ="align-self: center;"; ) {
Func2(); }
}

function Func1() {
    document.getElementById("Menu").style.display = "flex";
    document.getElementById("Submenu").style.display = "flex"; 
    document.getElementById("Menu_button").style.cssText ="align-self: center;"
    document.getElementById("Menu_button").getElementsByTagName("P")[0].innerHTML ="Close";   
}

function Func2() {
    document.getElementById("Menu").style.display = "none";
    document.getElementById("Submenu").style.display = "none"; 
    document.getElementById("Menu_button").style.cssText ="align-self: flex-end;"
    document.getElementById("Menu_button").getElementsByTagName("P")[0].innerHTML ="Menu"; 
}  

当然 if 条件也是如此:

   if ( document.getElementById("Menu_button").style.cssText ="align-self:flex-end;" == true) {
        Func1();
    }

我尝试了同样的操作 if textContent = "Menu" then do that...但是什么也没有。正如你所看到的,我正在学习 JavaScript,语法和含义仍然不太清楚。我希望有人能为我解决问题。


SOLUTION

如果你想获得元素的样式,你必须使用正确的方法。我在 MDN 网站上找到了它。

简单的例子:

<!DOCTYPE html>
<html>
<style>
h1 {
background-color:pink;
}
</style>
<body>

<button type="Button" onclick="Test();">Click me!</button>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<script>
function Test() {
var element = document.getElementsByTagName("h1")[0];
var stil = window.getComputedStyle(element).getPropertyValue("background-color"); 
    if (stil == "rgb(255, 192, 202)") {
        alert("OK");
    } else {
        alert("Not ok")
    }

}
</script>
</body>
</html>

您获得 RGB 形式的值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用元素的样式属性作为 if 或 for 循环 javascript 中的条件 的相关文章

随机推荐