javascript - 将显示从 'block' onclick 更改为 'none' 的功能不起作用

标签 javascript html css

我正在尝试使用 div 而不是 uls 制作可点击的下拉菜单。我的所有样式都正确,但我编写的函数不会切换可见性。有什么想法吗?

HTML

        <a href="#" name="menu" onclick="toggleMenu('menu-1.sub');"><div class="menu-item" id="menu-1"><a aria-haspopup="true" href="#">GET SUPPORT</a>
            <div class="sub-menu" id="menu-1.sub"></div>
        </div></a>



</div>

CSS

 div#mobile_menu_drop-down_test {display:block; position:absolute; top:35px; 
 left:20px; width:40px; height:40px; box-shadow:2px 2px 2px #000; 
background-color:#fff;  background-image:url(Images/hamburger.png); 
background-size:30px 20px; background-repeat:no-repeat; background-
position:center; cursor:pointer;
}

div#mobile_menu_wrapper {
display:none;
position:fixed;
top:0px;
left:0px;
width:100%;
height:auto;
background-color:#ffcb05;
color:#00274c;
box-shadow:2px 2px 5px #000;
font-weight:bold;
font-size:14px;
}

div.menu-item {
display:block; width:100%; border-bottom:1px dashed #5d5d5d; 
padding:15px 0px; text-indent:30px; transition:.2s ease;
}


div.sub-menu {display:none; text-indent:65px; padding:12px 0px; color:#fff;}


}

Javascript

function toggleMenu (id) {
var men = document.getElementById(id);
if (men.style.display =='none')
    men.style.display = 'block';
else
    men.style.display ='none';
}

最佳答案

您正在 CSS 中添加 display: none;element.style.display 检查元素上的内联样式。将您的 JavaScript 更改为:

var men = document.getElementById(id);
var display = men.currentStyle ? men.currentStyle.display :
                          getComputedStyle(men, null).display;
if (display == 'none' || men.style.display == 'none')
    men.style.display = 'block';
else
    men.style.display = 'none';
}

IE 使用 .currentStyle,但其他浏览器不使用(因此使用三元运算符)。其他浏览器使用 getCompulatedStyle(),因此我们根据浏览器使用正确的版本。

关于javascript - 将显示从 'block' onclick 更改为 'none' 的功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38149720/

相关文章:

javascript - Soundcloud JS SDK - 如果应用程序安装在 iOS 上,则 SC.Connect() 回调窗口无法关闭

JavaScript/ThreeJS 类型错误 : Cannot read property 'set' of undefined

android - 在 web View 和 TextView 中使用 html 颜色标签分隔阿拉伯语字体

css - 视网膜 Sprite 和高对比度模式

javascript - JQuery UI 拖入可排序不滚动

asp.net - 图像大小不适用于 mozilla 和 IE

javascript - 如何使用 Chrome 控制台更改颜色

javascript - jQuery Textillate.js - 如何 "reset"元素 html 并重新启动动画

jquery - 自定义图像 slider 问题(图像撞到新行)

html - 如何将菜单文本居中(边框底部)