切换CSS类对元素

时间:2016-12-30 23:11:11

标签: javascript html css

我正在尝试创建一个基本的JavaScript下拉菜单。我正在拨打一个名为" show,"它显示下拉内容。它不起作用 - 即使在应用类之后元素仍保持隐藏状态。

我想我在这里遇到了一个错误,但我似乎无法找到它。救命!



		function drop() {
			document.getElementById('content').classList.toggle('show');
		}

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

		<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:5)

问题不在于您的JavaScript,而在于您的CSS。

您的#content样式规则比.show规则更具体。当您启用和关闭.show规则时,#content规则会覆盖该规则,该规则会说明display应为none

有关哪些选择器会覆盖其他选择器的详细信息,请参阅 selector specificity 。还有一个 great site ,您可以测试选择器以查看它们的特异性。使用该网站的“计算器”,您可以看到基于id的选择器将始终覆盖“类”选择器。

ID selector is more specific that class selector.

解决方案是将#content选择器更改为类选择器,我在这里完成了(.menu)。这样,你将有两个影响下拉菜单的类选择器,它们都具有相同的特异性(覆盖另一个的那个将简单地由最后一个应用决定)。

function drop() {
  document.getElementById('content').classList.toggle('show');
}
.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;
}
<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>