我已经阅读了有关此内容的其他文章,但仍然无法按照我想要的方式工作。它确实应用了该类,但是未应用该类的内容。怎么了?
$(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>
答案 0 :(得分:1)
这似乎是CSS specificity的问题。
选择器.topBar button
的特异性比.active
高,因此其定义优先,并且background-color
的{{1}}被覆盖。
如果将.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;
}