我已经被这个问题困扰了大约 2 个小时。我想做的是一个网站,你按下一个按钮,它就会改变颜色。我知道这可以用 CSS 完成,但我对此不感兴趣。
主要问题是,当我按下按钮时,没有任何反应。但是,如果我从 css 中删除“#sug”,一切都会完美...所以我想做的是使布局非常一开始是基本的,所以除了黑色背景什么都没有,当我按下按钮时它应该切换..
此外,我知道您可以在按钮标记中实现 onclick
,但这也不是我想要的。我想知道为什么会发生这种情况以及如何解决这个问题。
这是我的 javascript、CSS 和 HTML 代码:
window.onload = setUp;
function setUp() {
document.getElementById("normal").onclick = setNormalStyle;
document.getElementById("crazy").onclick = setCoolStyle;
document.getElementById("insane").onclick = setInsaneStyle;
}
function setNormalStyle() {
var messageBox = document.getElementById("sug");
messageBox.className = "normal";
}
function setCoolStyle() {
var savingTheSecondVar = document.getElementById("sug");
savingTheSecondVar.className = "cool";
}
function setInsaneStyle() {
var savingTheThirdVar = document.getElementById("sug");
savingTheThirdVar.className = "insane";
}
#sug {
background-color: black;
}
.normal {
height: 500px;
background-color: blue;
color: white;
padding: 30px;
margin: auto;
width: 500px;
}
.insane {
height: 500px;
background-color: green;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
.cool {
height: 500px;
background-color: red;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="Struktur.css" />
<script type="text/javascript" src="struktur.js"></script>
<title>My first Javascript project</title>
</head>
<body>
<div id="sug" class="cool insane normal">
<header>
<h1> Welcome to this Javascript site! </h1>
</header>
<section>
<p>
text
</p>
</section>
<button type="button" id="normal">First style</button>
<button type="button" id="crazy">Second style</button>
<button type="button" id="insane">Third style</button>
</div>
</body>
</html>
最佳答案
问题出在您的 CSS。
#sug{
background-color: black;
}
覆盖类的背景颜色,因为它是一个更具体的选择器(即 id 选择器)。
更改 css 中的其余类以包含 id
#sug.normal、#sug.insane、#sug.cool 等
这里有一篇关于 CSS 特异性的好文章,可以帮助您了解更多:https://css-tricks.com/specifics-on-css-specificity/
关于javascript - 当我使用 Javascript 时,ID 接管了我的类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39583504/