jQuery 切换类让我难住了

标签 jquery css

我已经阅读了关于此的其他帖子,但它仍然没有按照我想要的方式工作。它确实应用了该类,但未应用该类的内容。出了什么问题?

$(document).ready(function() {
  $('button').click(function() {
    $(this).toggleClass("active");
  });
});
.topBar {
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

.topBar span {
  margin-right: 34%;
}

.topBar button,
span {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.topBar button:hover,
span:hover {
  background-color: #ddd;
  color: #333;
}

.topBar button {
  background-color: #333;
  border: none;
}

.active {
  background-color: red;
}
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="//stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

<div class="topBar">
  <span>Code Player</span>
  <div class="topButtons">
    <button id="html">HTML</button>
    <button id="css">CSS</button>
    <button id="javascript">JavaScript</button>
    <button id="output">Output</button>
  </div>
</div>

View On Codepen

最佳答案

这好像是CSS specificity的问题.

选择器.topBar button.active有更高的特异性,所以它的定义优先,background-color >.active 被覆盖。

如果把.active改成.topBar .active,会有更高的特异性。

$(document).ready(function() {
  $('button').click(function() {
    $(this).toggleClass("active");
  });
});
.topBar {
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

.topBar span {
  margin-right: 34%;
}

.topBar button,
span {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.topBar button:hover,
span:hover {
  background-color: #ddd;
  color: #333;
}

.topBar button {
  background-color: #333;
  border: none;
}

.topBar .active {
  background-color: red;
}
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="//stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

<div class="topBar">
  <span>Code Player</span>
  <div class="topButtons">
    <button id="html">HTML</button>
    <button id="css">CSS</button>
    <button id="javascript">JavaScript</button>
    <button id="output">Output</button>
  </div>
</div>

关于jQuery 切换类让我难住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52067156/

相关文章:

javascript - 使用 simplecartjs 在结帐前添加功能

javascript - 如何水平放置尽可能多的 <div>

html - 日历和文本不在一行中

html - CSS - float 和背景大小关系

html - 双击时更改文本颜色

jquery - 如何在链接下方显示div

javascript - 如何使弹出式 div 在单击时隐藏/显示

javascript - 如何使用正则表达式用新行替换段落元素?

html - 悬停在列表元素上的图像

javascript - 尝试检查负载上的下拉值,但它不起作用。