classをJavaScriptから動的に変えたい
現在作成中のウェブおみくじで、おみくじの結果によってテキストの色を変えたいと思っている。いろいろ考えた結果、HTMLのclassをJavaScriptから変更すれば良い感じでできそうだったので、やってみた。
getElementByIdを使ってやってみる
まず、HTMLを以下のように変更した。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<link rel = "stylesheet" href = "omikuji_element.css"/> | |
<script> | |
function tryFortune() { | |
var resultInt = Math.floor(Math.random () * 7) | |
switch (resultInt) { | |
case 0 : resultText = "大凶"; resultClass = "bad"; break; | |
case 1 : resultText = "凶"; resultClass = "bad"; break; | |
case 2 : resultText = "末吉"; resultClass = "normal"; break; | |
case 3 : resultText = "小吉"; resultClass = "normal"; break; | |
case 4 : resultText = "中吉"; resultClass = "good"; break; | |
case 5 : resultText = "吉"; resultClass = "good"; break; | |
default : resultText = "大吉"; resultClass = "good"; break; | |
} | |
document.getElementById("result").textContent = resultText; | |
document.getElementById("result").className = resultClass; | |
} | |
</script> | |
</head> | |
<body> | |
<h1>HTMLとJavaScriptによるWebおみくじ</h1> | |
<button onclick="tryFortune()">おみくじを引く</button> | |
<p id = "result"></p> | |
</body> | |
</html> |
各おみくじの結果によりgood、normal、badをresultClassという変数に代入し、最後に
document.getElementById(“result”).className = resultClass;
でClassを変更している。また、CSSを以下のように変更した。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
* { | |
font-size:20px; | |
} | |
h1 { | |
font-size:22px; | |
margin:20px; | |
} | |
p { | |
margin-left:175px; | |
padding:5px; | |
} | |
.button_omikuji { | |
width:160px; | |
height:40px; | |
margin-left:120px; | |
} | |
.bad{ | |
color:red; | |
} | |
.normal{ | |
color:green; | |
} | |
.good{ | |
color:blue | |
} |
good、normal、badにより、おみくじ結果のテキストの色が青、緑、赤に変更されるようにしている。これで、おみくじの結果によってテキストの色を変更することができた。(あまりスマートじゃない気はするが…。)
参考書籍
今はこの本を読みながらHTML、CSS、JavaScriptの勉強してます。書籍のコードをなぞるだけだと面白味が無いしブログにものっけられないので、本で勉強したことをもとに何かつくり、コードを公開していくスタイルで日記を書いてます。最終的にはWebブラウザ上で動くゲームをつくって公開したい。
ゲームを作りながら楽しく学べるHTML5 CSS JavaScriptプログラミング[改訂版] (Future Coders(NextPublishing)) |
+2