0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【jquery,js】表示する時間によって画像を変更する[switch,Date,append,html] [js09_20210227]

Last updated at Posted at 2021-02-26

処理の概要

ブラウザを開いた時、時間帯によって表示する画像を変えます。
index.htmlと同じ階層にimgフォルダを用意し、任意の画像を格納して下さい。

処理のフロー:

 (1)dateオブジェクトで時間を取得
 (2)ケース分岐して表示するためのファイルを指定する
 (3)jsで要素を追加し、画像を表示する

画面イメージ

#####画像1

時間帯によって表示される画像が変わります。今は、7時なのでこの画像が表示されます。他の画像を貼り付けるのが面倒なので、今回はこれだけです。

ソースコード

index.html
<head>
<link rel="stylesheet" href="./css/default.css">
</head>
<body>
<div id="timeBackImage"></div>
</body>
main.js
// DOMの準備後に実行する内容
$(function() {
    var ldateObj = new Date();
    var currentTime = ldateObj.getHours();
    var lfileName = "";

    switch(true){
        case (0 <= currentTime && currentTime < 5):
            lfileName = 'night.png';
            break;
        case (5 <= currentTime && currentTime < 12):
            lfileName = 'morning.png';
            break;
        case (12 <= currentTime && currentTime < 18):
            lfileName = 'daytime.png';
            break;
        case (18 <= currentTime && currentTime < 24):
            lfileName = 'night.png';
            break;
    }

//   // 時間による分岐
//   if (0 <= h && h < 7) {
//     fileName = "night.png";   // 夜  0~ 6時 night.png
//   } else if (7 <= h && h < 12) {
//     fileName = "morning.png"; // 朝  7~11時 morning.png
//   } else if (12 <= h && h < 19) {
//     fileName = "daytime.png"; // 昼 12~18時 daytime.png
//   } else if (19 <= h && h < 24) {
//     fileName = "night.png";   // 夜 19~23時 night.png
//   }

    var addImageTag = $("<img>");
    addImageTag.attr("src","img/" + lfileName);
    $("#timeBackImage").append(addImageTag);
});
default.css
img {
	width: 300px;
	height: 200px;
}

ポイント

html:
(1)なし
js:
(1)Dateオブジェクトを作成し、現在時刻を取得する準備をする
(2)※switchメソッドはこの使い方は可読性を下げます。ifとelseifで分けた方がいいです。
(3)htmlメソッドではなく、appendで子要素として追加します

参考資料

JavaScript(仕事の現場でサッと使える!デザイン教科書) p130

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?