私は2時間ほどこの問題を抱えていました。私がしようとしているのは、ボタンを押して色を変えるウェブサイトです。私はこれがCSSでできることを知っていますが、私はそれに興味がありません。Javascriptを使用しているときにIDが私のクラスを引き継いでいます
主な問題は、私がボタンを押したときに何も起こらないということです。しかし、「#sug from the css」を削除すると、すべてが完璧に動作します...私がしたいのは、レイアウト非常に基本的なものなので、黒い背景のようなものはありません。ボタンを押すと切り替えるはずです。
さらに、onclick
をボタンタグに実装できます私はどちらかに行きます。私はこれがなぜ起こり、どうやってこの問題を解決できるのか知りたい。
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/ - トピックに関する素敵な記事 –
今日、デファクトスタンダードは、CSSのIDをまったく使わないことです。 javascriptのみです。 – ippi