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 1 year has passed since last update.

javaScriptで固定されたD-Dayを作り方

Last updated at Posted at 2022-07-05
  • 固定された入力値
     ⇒クリスマスのD-Day

必要なページ

1.index.html
  ⇒画面に表示されるページ
2. index.js
  ⇒機能のページ


固定された入力値

INDEX.HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Time Until Christmas Eve</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <h1>Time Until Christmas Eve</h1>
    <h2 class="js-clock"></h2>
    <script src="index.js"></script>
  </body>
</html>

INDEX.JS

const clockTitle = document.querySelector(".js-clock");

function clock(){
  const dday = new Date("Dec 25, 2022, 00:00:00").getTime();
  let today = new Date();
  let dClock = dday - today;
  let chrD = Math.floor(dClock / (1000*60*60*24));
  let chrH = Math.floor(dClock / (1000*60*60)%24);
  let chrM = Math.floor(dClock / (1000*60)%60);
  let chrS = Math.floor(dClock / 1000%60);
  
  chrD = String(chrD).padStart(2, "0");
  chrH = String(chrH).padStart(2, "0");
  chrM = String(chrM).padStart(2, "0");
  chrS = String(chrS).padStart(2, "0");

  clockTitle.innerText = `${chrD}d ${chrH}h ${chrM}m ${chrS}s`;

 if(dday < today){
   return clockTitle.innerText = "Merry christmas!";
  }
}

clock();
setInterval(clock, 1000);
  1. document.querySelector : class="js-clock"の一番目の要素を持つ
  2. clock() : 他のイベントがないからすぐ作動
    getTime() : Date(値)をmillisecond(1/1000秒)で返還
      ⇒Math.floor : Math.floor(値)の最大の定数を変換
  3. padStart() : 望む様 01、02 / 出る様 1、2
      ⇒ 表示 : 2 、なければ 0
  4. innerText : TEXTで入力
  5. setInterval(clock, 1000) : 1秒ごとに実行

完成場面

  • CSS変更は自身の好み
0
0
2

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?