我正在尝试使用 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/