我一直坐在這個問題上2小時。我試圖做的是一個網站,你按下一個按鈕,它會改變顏色。我知道這可以用CSS完成,但我對此不感興趣。當我使用Javascript時,ID正在接管我的課程
主要問題是,當我按下按鈕時,什麼也沒有發生..但是,如果我從'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>
ID規則將否決類規則。這就是CSS的工作原理。 –
https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/ - 關於主題的一篇很好的文章 –
現在事實上的標準是根本不使用ID的CSS - 僅適用於JavaScript。 – ippi