J S*_*olt 0 html javascript css
我正在尝试创建一个基本的JavaScript下拉菜单.我正在切换一个名为"show"的类,它显示下拉内容.它不起作用 - 即使在应用类之后元素仍保持隐藏状态.
我想我在这里有一个错误,但我似乎无法找到它.救命!
function drop() {
document.getElementById('content').classList.toggle('show');
}Run Code Online (Sandbox Code Playgroud)
.container {
display: inline-block;
position: relative;
}
.dropdown_btn {
color: white;
background-color: black;
cursor: pointer;
padding: 20px;
}
.dropdown_btn:hover, .dropdown_btn:focus {
background-color: grey;
}
#content {
display: none;
position: absolute;
background: grey;
color: white;
width: 160px;
}
.container a {
text-decoration: none;
display: block;
padding: 10px;
color: white;
}
.container a:hover {
background-color: #f1f1f1
}
.show {
display: block;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<button class="dropdown_btn" onclick="drop()">Menu</button>
<div id="content">
<a href="">Link 1</a>
<a href="">Link 2</a>
<a href="">Link 3</a>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
您的#content样式规则比您的.show规则更具体.当您.show打开和关闭规则时,#content规则会覆盖它,并且该规则display应该是none.
有关哪些选择器将覆盖其他选择器的更多信息,请参阅选择器特 还有一个很棒的网站,你可以测试选择器,看看它们的特异性.使用该网站的"计算器",您可以看到id基于选择器将始终覆盖"类"选择器.
解决方案是将#content选择器更改为类选择器,我在这里完成了(.menu).这样,你将有两个影响下拉菜单的类选择器,它们都具有相同的特异性(覆盖另一个的那个将简单地由最后一个应用决定).
function drop() {
document.getElementById('content').classList.toggle('show');
}Run Code Online (Sandbox Code Playgroud)
.container {
display: inline-block;
position: relative;
}
.dropdown_btn {
color: white;
background-color: black;
cursor: pointer;
padding: 20px;
}
.dropdown_btn:hover, .dropdown_btn:focus {
background-color: grey;
}
/* This used to be an id based selector (#content), but that
type of selector is more specific than a class selector so
toggling the class selector had no effect. */
.menu {
display: none;
position: absolute;
background: grey;
color: white;
width: 160px;
}
.container a {
text-decoration: none;
display: block;
padding: 10px;
color: white;
}
.container a:hover {
background-color: #f1f1f1
}
/* This is the class that will be toggled on and off.
Because the CSS rule that hides this menu uses a
class selector, another class selector can override it. */
.show {
display: block;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<button class="dropdown_btn" onclick="drop()">Menu</button>
<div id="content" class="menu">
<a href="">Link 1</a>
<a href="">Link 2</a>
<a href="">Link 3</a>
</div>
</div>Run Code Online (Sandbox Code Playgroud)