JavaScript: задача по созданию HTML-календаря
Эта функция должна создать календарь за указанный месяц указанного года в виде HTML-таблицы и поместить эту HTML-таблицу в указанный контейнер calendar . На HTML-странице в браузере такая таблица-календарь должна выглядеть примерно так:
пн | вт | ср | чт | пт | сб | вс |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
HTML-таблица создается с помощью HTML-элементов table (таблица целиком), tr (строки таблицы, представляющие недели), th (ячейки заголовочной части таблицы, содержащие сокращенные названия дней недели) и td (ячейки таблицы, содержащие даты).
Итак, наша задача — написать функцию:
function createCalendar(elem, year, month) < // . наш код . >
Очевидно, что должен быть некий цикл, в котором будем проходить даты заданного временного промежутка. Следовательно, должна быть некая переменная, назовём ее cur_date , которая будет содержать текущую дату и служить чем-то вроде счетчика (будем листать ее день за днем). Меняем код:
function createCalendar(elem, year, month) < let cur_date = new Date(year, month - 1, 1); // текущая дата while ( ) < // цикл > >
Начальным значением переменной cur_date возьмём первое число заданного месяца заданного года. Тут нужно отметить, что пользователь нашей функции задаёт месяц целым числом от 1 до 12, а в языке JavaScript месяцы представляются целым числом от 0 до 11 (даты — числом от 1 до 31). Поэтому мы должны вычесть из переменной month единицу, чтобы получить нужное представление месяца для JavaScript.
Так как таблицу в любом случае необходимо начать строить с понедельника, то нужно отмотать наш счетчик cur_date в прошлое до ближайшего понедельника (он может быть в предыдущем месяце). Меняем код:
function createCalendar(elem, year, month) < let cur_date = new Date(year, month - 1, 1); // текущая дата while ( cur_date.getDay() != 1 ) < // находим ближайший понедельник cur_date.setDate(cur_date.getDate() - 1); // слева > while ( ) < // основной цикл > >
Дни недели в языке JavaScript представляются целым числом от 0 до 6, причем отсчет начинается с воскресенья (обозначается нулем), понедельник обозначается единицей и так далее до субботы, которая обозначается числом 6. День недели определяем по текущей дате в переменной cur_date с помощью метода getDay . Условие продолжения работы цикла cur_date.getDay() != 1 читается как «пока не найден понедельник».
Основной цикл у нас будет листать недели, а внутри основного цикла создадим подцикл, который будет строить очередную неделю. Меняем код:
function createCalendar(elem, year, month) < let cur_date = new Date(year, month - 1, 1); // текущая дата while ( cur_date.getDay() != 1 ) < // находим ближайший понедельник cur_date.setDate(cur_date.getDate() - 1); // слева > while ( ) < // основной цикл (строим таблицу) for (let i = 0; i < 7; i++) < // строим очередную неделю > > >
function createCalendar(elem, year, month) < let cur_date = new Date(year, month - 1, 1); // текущая дата while ( cur_date.getDay() != 1 ) < // находим ближайший понедельник cur_date.setDate(cur_date.getDate() - 1); // (листаем дату назад) > let table = document.createElement("table"); while ( /* условие */ ) < // строим таблицу let tr = document.createElement("tr"); for (let i = 0; i < 7; i++) < // строим очередную неделю let td = document.createElement("td"); td.textContent = cur_date.getDate(); tr.append(td); cur_date.setDate(cur_date.getDate() + 1); // листаем дату вперёд > table.append(tr); > elem.append(table); // добавляем таблицу в заданный контейнер >
Синим пометил места, в которых создаются конкретные HTML-элементы.
Цикл построения таблицы должен завершиться, когда текущая дата cur_date выйдет в следующий месяц. Чтобы засечь этот момент, я создал еще одну переменную fin_date , содержащую последнюю дату заданного месяца. Тогда условием продолжения цикла можно взять cur_date
Кроме этого, нужно добавить заголовок таблицы с сокращенными названиями дней недели.
И последнее — поставим на строку вывода очередной даты td.textContent = cur_date.getDate(); условие, при котором будут выводиться только даты заданного месяца.
function createCalendar(elem, year, month) < let cur_date = new Date(year, month - 1, 1); // текущая дата let fin_date = new Date(year, month, 0); // последняя дата заданного месяца while ( cur_date.getDay() != 1 ) < // находим ближайший понедельник cur_date.setDate(cur_date.getDate() - 1); // (листаем дату назад) > let table = document.createElement("table"); // заголовок таблицы table.innerHTML = ""; while ( cur_date // строим таблицу let tr = document.createElement("tr"); for (let i = 0; i < 7; i++) < // строим очередную неделю let td = document.createElement("td"); if ( cur_date.getMonth() == month - 1 ) < // показывать только даты заданного td.textContent = cur_date.getDate(); // месяца > tr.append(td); cur_date.setDate(cur_date.getDate() + 1); // листаем дату вперёд > table.append(tr); > elem.append(table); // добавляем таблицу в заданный контейнер > пн вт ср " + "чт пт сб вс
Календарь-2 для сайта на JavaScript
Еще одиин простой календарь для сайта на CSS и JavaScript.
Этот Пример 2 отличается от календаря Пример 1 тем, что в нем прорисованы ячейки таблицы. Цвет ячеек можно менять, под цвета своего сайта.
- Разместить все три части на одной странице.
- Разместить часть 1 (стиль календаря) в отдельном файле.css.
- Разместить часть 3 (скрипт календаря) в отдельном файле.js и подключить к странице сайта.
1. Стиль календаря
/* Таблица календаря */ .calendar < border: 1px solid #909090; border-collapse: collapse; font-family: Arial; font-size: 11px; >/* Заголовок */ .calendar th < text-align: center; width: 26px; height: 20px; background: #e2f2fc; color: #000000; border: 1px solid #909090; >/* Заголовок праздника */ .calendar th.holiday < color: #FF0000; >/* Ячейка дня */ .calendar td < text-align: right; width: 20px; height: 20px; padding-right: 4px; border: 1px solid #909090; text-align: right; cursor: pointer; font-size: 12px; >/* Затемненный день */ .calendar td.grayed < background: #F0F0F0; cursor: auto; >/* Выбранный день */ .calendar td.selected < background: #038fcf; color: #FFFFFF; box-shadow: 1px 1px rgba(255, 255, 255, 0.5) inset; >/* Праздничный день */ .calendar td.holiday < color: #FF0000; >/* Кнопки навигации */ .calendar td.navigation
2. Код календаря на страние сайта.html
3. Скрипт календаря
How To Create A Simple Calendar Using HTML
Calendars are a necessary part of our everyday life, they help us stay organized, focused and on top of tasks we need to complete each day. So why not make one with HTML? It’s fun and simple. In this tutorial I’ll show you how to create a very basic calendar using HTML Tables!
If you’d like to read some basic on HTML Tables read my How To Create A Basic Table Using HTML tutorial!
This is the simple calendar we are going to create, it’s not pretty but it will give you the basis you need to create fancier calendars in the future!
December 2013 | ||||||
---|---|---|---|---|---|---|
Su | Mo | Tu | We | Th | Fri | Sat |
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
First we need to create the basic HTML Element for our calendar.
(— HTML tags and information are going here — do not copy this line of information —)
Next we need to add our calendar title which is the Month and Year of our choosing. We will be using the title header tags because they show up bold and we need them to stand out.
You’ll notice that the Table Header has an attribute within in it which is colspan=»7″. This simply allows that Header row to stretch across all of the columns below and create a nice title area! The number 7 can be changed to any number. In this particular exercise the calendar has 7 rows for 7 days of the week. The title stretches above all 7 rows which is why we used that number.
Next we are going to add in our Days of the Week columns below the calendars title tags.
Next we are going to add our first row of Numbered Cells representing individual days of the month! This set of HTML Tags will be placed underneath the Days of the Week columns you just placed into the coding.
To do this we will now be using the tags, also known as the Table Data tags. These tags are used to plug in information into an HTML Table and unlike the title tags they will not show up bold, which is just what we want.
This is what our current calendar should look like so far:
December 2013 | ||||||
---|---|---|---|---|---|---|
Su | Mo | Tu | We | Th | Fri | Sat |
1 | 2 | 3 | 4 | 5 | 6 | 7 |
Now we just need to complete the rows and columns and plug in the correct numbers by copying the last set of tags and information we used for the numbered cells we created and pasting them below each other!
You’re ending result should like like the calendar below!
December 2013 | ||||||
---|---|---|---|---|---|---|
Su | Mo | Tu | We | Th | Fri | Sat |
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
If you’d like to check out a fancy HTML calendar view my Smooth HTML Calendar Styled With CSS post!