使用元素的样式属性作为if或for循环javascript中的条件 [英] Use style property of an element as condition in if or for loop javascript

查看:89
本文介绍了使用元素的样式属性作为if或for循环javascript中的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解If语句[或For lopp]中的条件时遇到问题。我创建了像菜单按钮一样播放的div。当我单击该div时,将显示包括该菜单按钮的所有菜单,但文本[div内的段落]也会变为关闭菜单。我试图在菜单按钮中启动某些if条件,但条件似乎无法正常运行。下面是for循环中的示例:

I am having problems understanding condition in If statement [or For lopp]. I created div that plays like Menu button. When I click that div all menu including this Menu button is shown but also text [paragraph inside div] changes to "Close menu". I tried to make some if condition in function that is fired up when I click Menu button but it looks like if condition doesn't work like I want to. Here is an example in for loop:

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 ( document.getElementById("Menu_button").style.cssText ="align-self:flex-end;" == true) {
        Func1();
    }

如果textContent = Menu,我尝试过相同的操作。但是什么都没有。如您所见,我正在学习JavaScript和语法,其含义仍不清楚。我希望有人能为我解决问题。

I tried the same with if textContent = "Menu" then do that... But nothing. As you can see I am learning JavaScript and syntax and meaning still isn't quite clear. I hope someone could clear things up for me.

推荐答案

解决方案

如果要获取元素的样式,则必须使用适当的方法。我在MDN网站上找到了它。

If you want get style of an element you have to use proper methods. I found it on MDN site.

简单示例:

<!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形式获得价值。

You get value in rgb form.

这篇关于使用元素的样式属性作为if或for循环javascript中的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆