gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:25:56 24 4
gpt4 key购买 nike

我在理解 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"尝试了同样的方法,然后这样做……但什么也没有。如您所见,我正在学习 JavaScript,语法和含义仍然不是很清楚。我希望有人能为我解决问题。

最佳答案

解决方案

如果你想获得一个元素的样式,你必须使用正确的方法。我在 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 形式的值。

关于javascript - 使用元素的样式属性作为 if 或 for 循环 javascript 中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31817685/

24 4 0
文章推荐: html -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com