我正在尝试获取一个下拉菜单,以显示屏幕大小小于500px的时间。稍后,我将删除导航栏,以便此菜单在小型设备上替换它。
代码对我来说很好,警报会启动,但菜单没有显示。
TLDR:当屏幕尺寸小于500像素时需要显示菜单
JSFiddle:https://jsfiddle.net/mcgettrm/y4edsu73/
代码:
var dropDownFunction = function(){
var menuContent = document.getElementById("dropDownMenuClass");
menuContent.classList.toggle("menuShow");
}
var windowWidth = window.innerWidth;
if(windowWidth < 500){
alert("window is too small");
var dropDownMenu = getElementById("dropDownMenu");
dropDownMenu.classList.toggle("mainMenuShow");
}
#dropDownMenu {
}
.dropDownMenuClass{
display:none;
}
.mainMenuShow{
display: block;
}
#dropDownMenuContent {
}
.dropDownMenuContentClass {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
width:100%;
text-align: center;
}
#dropDownMenuContent a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
#dropDownMenuContent a:hover {
background-color: #f1f1f1;
}
#dropDownButton {
width:100%;
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.menuShow {
display: block;
}
<div id="dropDownMenu" class="dropDownMenuClass">
<button onclick="dropDownFunction()" id="dropDownButton">MENU</button>
<div id="dropDownMenuContent" class="dropDownMenuContentClass">
<a href="index.html">Home</a>
<a href="about.html">About</a>
<a href="itprojects.html">IT Projects</a>
<a href="languageprojects.html">Language Projects</a>
<a href="contact.html">Contact</a>
<a href="essays.html">Essays</a>
</div>
</div>
答案 0 :(得分:2)
getElementByID
是document
var dropDownMenu = document.getElementById("dropDownMenu");
答案 1 :(得分:1)
始终检查控制台是否有错误。例如,在Chrome中,您将看到
Uncaught ReferenceError: getElementById is not defined
应该是:
var dropDownMenu = document.getElementById("dropDownMenu");