JavaScriptでページの背景色や前景色を変更するコードを紹介します。
javaScriptでページの背景色を変更する場合は"document"クラスの"bgColor"プロパティにカラーを設定します。ページの前景色を変更する場合は、"document"クラスの"fgColor"プロパティにカラーを設定します。
以下のコードを記述します。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript">
document.bgColor = "#202020";
document.fgColor = "#E0E0E0";
</script>
</head>
<body>
ページです。
</body>
</html>
JavaScriptのコードの
document.bgColor = "#202020";
document.fgColor = "#E0E0E0";
の部分で、documentクラスのbgColor,fgColorプロパティにカラーを設定しています。
上記のHTMLファイルを表示します。下図の結果となります。
ページの背景色と文字色が変更できています。
以下のコードを記述します。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript">
function SetColor(foreColor, backColor) {
document.bgColor = document.form1.Text1.value;;
document.fgColor = document.form1.Text2.value;;
}
</script>
</head>
<body>
<form name="form1" action="">
前景色<input id="Text1" type="text" /><br />
背景色<input id="Text2" type="text" /><br />
<input id="Button2" type="button" value="button" onclick="SetColor()"/>
</form>
</body>
</html>
JavaScriptのコードの
function SetColor(foreColor, backColor) {
document.bgColor = document.form1.Text1.value;;
document.fgColor = document.form1.Text2.value;;
}
の部分でテキストボックスに入力された値を、documentオブジェクトのbgColor,fgColorプロパティに設定します。
SetColor関数は
<input id="Button2" type="button" value="button" onclick="SetColor()"/>
の記述により、[button]がクリックされた際に呼び出されます。
上記のHTMLファイルをブラウザで表示します。下図の画面が表示されます。
テキストボックスにカラーコードを入力します。入力ができたら[button]を押します。
テキストボックスに入力したカラー値にページの背景色と前景色が変更されました。
CSSのスタイルを変更してページの背景色を変更する方法もあります。詳しくはこちらの記事を参照してください。