[英]How to do Javascript Function which will change the style display of element?
function burgerMenu(){
//alert(document.getElementById("hiddenMenuUL").style.display);
if(document.getElementById("hiddenMenuUL").style.display="none"){
document.getElementById("hiddenMenuUL").style.display="block";
}
else if(document.getElementById("hiddenMenuUL").style.display="block"){
document.getElementById("hiddenMenuUL").style.display="none";
}
}
I want to toggle the burger menu icon.我想切换汉堡菜单图标。 So if I press the icon the burgerMenu() function will be toggle and verify if its display: none then change to display:block and vice versa.因此,如果我按下图标, burgerMenu() 函数将被切换并验证其 display: none 然后更改为 display:block ,反之亦然。 hiddenMenuUL is the for list of links. hiddenMenuUL 是链接列表。 This line below is the button line in HTML:下面这一行是 HTML 中的按钮行:
<button class="btn" onclick="burgerMenu()">☰</button>
My CSS for hiddenMenuUL我的 hiddenMenuUL 的 CSS
#hiddenMenuUL{
display: none;
list-style: none;
width: 100%;
justify-content: center;
}
When you are writing your if, you are not actually checking if the display === "none", you are trying to set it to none.当您编写 if 时,您实际上并没有检查 display === "none" 是否显示,而是尝试将其设置为 none。
What you should be doing looks like this:你应该做的事情是这样的:
function burgerMenu(){
let menuStyle = document.getElementById("hiddenMenuUL").style.display;
if(menuStyle === 'none'){
document.getElementById("hiddenMenuUL").style.display="block";
}
else {
document.getElementById("hiddenMenuUL").style.display="none";
}
}
Edit:编辑:
It seems display rule is defined in CSS, and isn't inline.似乎显示规则是在 CSS 中定义的,而不是内联的。
.style can only reach inline styles, for example: .style 只能达到内联样式,例如:
<div id="hiddenMenuUL" style="display: none;"></div>
Adding 'display: none' inline like in the example above should be the fastest and easiest way to 'fix' it in your particular scenario, although it probably wouldn't be considered the best practice.添加 'display: none' 像上面的例子一样内联应该是在您的特定场景中“修复”它的最快和最简单的方法,尽管它可能不会被认为是最佳实践。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.