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



我在If语句[或For lopp]中理解条件有问题。我创建了像菜单按钮一样的div。当我点击该div所有菜单包括这个菜单按钮显示,但也文本[段落内div]更改为"关闭菜单"。我试图使一些如果条件的功能,是触发当我点击菜单按钮,但它看起来像如果条件不像我想要的工作。下面是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();
    }

我尝试了相同的如果textContent = "Menu"然后这样做…但是什么都没有。正如你所看到的,我正在学习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>

最新更新