JavaScriptは動的サイトを作成することが可能である。今回はスタイルの変更方法を3つ紹介します。
DOM要素を取得してclassNameプロパティの値を変更する方法です。
下のソースコードにおけるid名fooのdiv要素がこちらの方法にあたります。
mouseoverイベントとmouseoutイベントを登録しておき、イベント発生時にstyle.cssで予め用意してあった.foo-beforeと.foo-afterを交換しています。
また別の方法としてclassListを使用する方法がありあます。
toggleメソッドはtoggle(clazz)のように記述し、class名にclazzが含まれていれば削除、含まれていなければ追加するものです。
他にもaddメソッドやremoveメソッド、containsメソッドが存在します。
var foo = document.getElementById('foo');
foo.onclick = function toggleStyle() {
this.classList.toggle('foo-before');
this.classList.toggle('foo-after');
}
DOM要素を取得してstyleプロパティから各スタイルに対応するプロパティを参照し、値を変更する方法です。
下のソースコードにおけるid名barのdiv要素がこちらの方法にあたります。
こちらもmouseoverイベントとmouseoutイベントを登録しておき、イベント発生時にstyle.cssの.barを直接変更しています。
stylehsheetを複数用意し、それらにid名を割り当てておくことで、style要素のdisabledプロパティのtrueとfalseを変更します。
下のソースコードにおけるid名bazのdiv要素がこちらの方法にあたります。
style-a.cssとstyle-b.cssを切り替えることでスタイルを変更しています。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta lang='en'>
<link rel='stylesheet' href='style.css'>
<link rel='stylesheet' href='style-a.css' disabled='true' id='style-a'>
<link rel='stylesheet' href='style-b.css' disabled='false' id='style-b'>
<script src='script.js'></script>
<title></title>
</head>
<body>
<h1>スタイルの変更方法</h1>
<div id='foo' class='foo-before'>classの変更</div>
<div id='bar' class='bar'>styleの変更</div>
<div id='baz' class='baz'>stylesheetの変更</div>
</body>
</html>
window.onload = function() {
var foo = document.getElementById('foo');
foo.onmouseover = function() {
this.className = 'foo-after';
}
foo.onmouseout = function() {
this.className = 'foo-before';
}
var bar = document.getElementById('bar');
bar.onmouseover = function() {
var style = this.style;
style.backgroundColor = 'black';
style.color = 'white';
}
bar.onmouseout = function() {
var style = this.style;
style.backgroundColor = 'white';
style.color = 'black';
}
var baz = document.getElementById('baz');
baz.onmouseover = function() {
document.getElementById('style-a').disabled = true;
document.getElementById('style-b').disabled = false;
}
baz.onmouseout = function() {
document.getElementById('style-a').disabled = false;
document.getElementById('style-b').disabled = true;
}
}
.foo-before {
background-color: white;
color: black;
}
.foo-after {
background-color: black;
color: white;
}
.bar {
background-color: white;
color: black;
}
.baz {
background-color: white;
color: black;
}
.baz {
background-color: black;
color: white;
}