好玩的.日历

版权声明:个人笔记,不喜勿喷 https://blog.csdn.net/qq_39571197/article/details/88994771

不是算法,因为没有计算闰年、平年什么的。

用JS的Date对象实现一个日历,我想这是最简单的方式了吧..

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>calendar</title>
</head>
<body>
<input type="text" id="idYear" value="2019" onchange="display()">
<input type="text" id="idMonth" value="1" onchange="display()">
<section id="idCalendar">

</section>
<script>
	function genNextDays(target, pivot, total) {
		let targetYear = pivot.year;
		/**
		 * 此处做了转换,new Date(2018, 0, 0) === 2017年12月31日,new Date(2018, 1, 0) === 2018年1月31日
		 *
		 * 正常情况:new Date(2018, 0, 1) === 2018年1月1日,new Date(2018, 1, 1) === 2018年2月1日
		 * */
		let targetMonth = pivot.month + 1;
		let lastDayOfMonth = new Date(targetYear, targetMonth, 0).getDate();
		let day = pivot.day;
		for (let i = 0; i < total; i++) {
			day += 1;
			if (day > lastDayOfMonth) {
				day = 1;
				targetMonth++;
				lastDayOfMonth = new Date(targetYear, targetMonth, 0).getDate();
				// 更新之后,判断是否合法
				if (targetMonth > 12) {
					targetYear++;
					targetMonth = 1; // *
				}
			}
			target.push([targetYear, targetMonth, day].toString());
		}
	}

	function genPrevDays(target, pivot, total) {
		const lastDayOfPrevMonth = new Date(pivot.year, pivot.month, 0).getDate();
		let day = pivot.day;
		for (let i = 0; i < total; i++) {
			day -= 1;
			if (day === 0) {
				day = lastDayOfPrevMonth;
			}
			target.unshift(day);
		}
	}

	function genCalendar({date = new Date(), row = 6} = {}) {
		const WEEK_DAYS = 7;
		const currentDetail = {
			year: date.getFullYear(),
			month: date.getMonth(),
			day: date.getDate(),
		};
		const days = [];
		const CURRENT_WEEK = date.getDay();
		genPrevDays(days, currentDetail, CURRENT_WEEK - 0); // 从星期日0开始,这里可配置
		days.push(currentDetail.day);
		genNextDays(days, currentDetail, (WEEK_DAYS * row - 1) - CURRENT_WEEK);
		return days;
	}

	function display() {
		const year = idYear.value; // id variable
		const month = idMonth.value - 1; // id variable
		const days = genCalendar({
			date: new Date(year, month),
			row: 500,
		});
		let html = `<table width="100%" border="1" style="border-collapse: collapse;text-align: center;">`;
		for (let i = 0; i < days.length;) {
			if (i % 7 === 0) {
				html += '<tr>';
			}
			html += `<td>${days[i]}</td>`;
			i++;
			if (i % 7 === 0) {
				html += '</tr>';
			}
		}
		idCalendar.innerHTML = html;
	}

	display();
</script>
</body>
</html>

 

没有更多推荐了,返回首页