Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8764

Javascript カレンダー作成

$
0
0
はじめに 本稿では下記動画にあるソースコードを解説します。 動画にあるカレンダーは、他のライブラリに依存しない実装になっています。 簡単なカレンダーが表示できれば十分、かつ、依存ライブラリを増やしたくない場合などで使えると思います。 ソースコード https://github.com/lashaNoz/Calendar カレンダー作成に必要な変数 // 今日の日付 EX) 2021/11/24 const date = new Date(); // 月末 EX) 2021/11/30 const lastDay = new Date(date.getFullYear(),date.getMonth() + 1,0).getDate(); // 先月末 EX) 2021/10/31 const prevLastDay = new Date(date.getFullYear(),date.getMonth(),0).getDate(); // 月初の曜日。0 ~ 6 = 日曜 ~ 土曜 EX) 1 (2021/11/1は月曜日) const firstDayIndex = date.getDay(); // 月末の曜日。 EX) 2 (2021/11/30は火曜) const lastDayIndex = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDay(); 日付表示 calndar.js // 1.前の月 // firstDayIndexは月初の曜日。EX) 1(月曜) // prevLastDayは先月の末日。EX) 31 (10/31) for(let i = firstDayIndex; i>0; --i){ days += `<div class="prev-date">${prevLastDay - i + 1}</div>`; } // 2.今月 const today = new Date().getDate(); for(let i = 1; i<=lastDay; ++i){ if(i === today){ days += `<div class="today">${i}</div>`; } else { days += `<div>${i}</div>`; } } // 3.次の月 const sunday = 6; for(let i = 1; i<=sunday-lastDayIndex; ++i){ days += `<div class="prev-date">${i}</div>`; } 前月、次月表示ボタン押下時処理 document.querySelector(".prev").addEventListener("click", () => { // 前月のカレンダーを表示 date.setMonth(date.getMonth() - 1); renderCalendar(); }); document.querySelector(".next").addEventListener("click", () => { // 次月のカレンダーを表示 date.setMonth(date.getMonth() + 1); renderCalendar(); }); DOM読み込み完了後にJavascript実行(おまけ) 動画の実装だと、javascriptを読み込むタイミングによってはカレンダーが表示されません。 windows.onload内に処理を定義することで、DOM読み込みが完了した後に処理が実行されます。 window.onload = function(){ // 諸々の処理 const date = new Date(); const renderCalendar = function(){ date.setDate(1); ~~~ }

Viewing all articles
Browse latest Browse all 8764

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>