【问题标题】:How to do Javascript Function which will change the style display of element?如何做改变元素样式显示的Javascript函数?
【发布时间】:2020-02-20 08:39:06
【问题描述】:
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";
            }
    }

我想切换汉堡菜单图标。因此,如果我按下该图标,burgerMenu() 函数将被切换并验证其是否显示:无,然后更改为显示:块,反之亦然。 hiddenMenuUL 是链接列表。 下面这一行是 HTML 中的按钮行:

<button class="btn" onclick="burgerMenu()">&#9776;</button>

hiddenMenuUL 的 CSS

#hiddenMenuUL{
        display: none;
        list-style: none;
        width: 100%;
        justify-content: center;
    }

【问题讨论】:

  • protip:不要直接使用JS设置样式属性。相反,在 .css 文件中包含显示或隐藏元素的普通 CSS 类,然后使用 element.classList.add(...)element.classList.remove(...) 和/或 element.classList.toggle(...) 切换这些类。请参阅the docs for .classList 了解更多信息。
  • .style 仅包含内联样式,不包含来自 CSS 的样式。所以第一次调用函数时,可能找不到你要找的样式。

标签: javascript html css


【解决方案1】:

当您编写 if 时,实际上并没有检查 display === "none",而是尝试将其设置为 none。

你应该做的看起来像这样:

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";
            }
    }

编辑:

似乎显示规则是在 CSS 中定义的,而不是内联的。

.style 只能达到内联样式,例如:

<div id="hiddenMenuUL" style="display: none;"></div>

像上面的例子一样添加'display: none'应该是在你的特定场景中'修复'它的最快和最简单的方法,尽管它可能不会被认为是最佳实践。

【讨论】:

  • 它现在可以工作,但是由于某种原因,当我第一次单击时它进入 if 语句但第一次单击时没有打开它,但是如果我再次按下切换选项然后如果我继续垃圾邮件它会立即打开和关闭。由于某种原因,它在let menuStyle = document.getElementById("hiddenMenuUL").style.display; 行中为空
  • 您应该在关于 .style 仅查找内联样式的问题下参考 Barmar 的评论。或者,您可以编辑您的问题并提供 HTML/CSS 代码,以绘制整个画面。
  • 如果我在控制台记录它,这行代码应该输出“无”:let menuStyle = document.getElementById("hiddenMenuUL").style.display; 但第一次点击时它是空的
  • 是的,它不会记录任何内容,因为它无法达到 CSS 规则,因为它没有设置为内联。之后,if/else 看到 menuStyle 不是“无”,因此它为 hiddenMenuUL 提供了无的内联显示,之后一切都按预期工作。查看我编辑的答案,以最快的方式解决这个问题。
  • 哇,谢谢它的工作。有没有达到 CSS 规则的实际方法?
猜你喜欢
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-20
相关资源
最近更新 更多