简易 javascript 日历
程序员文章站
2022-03-03 22:33:31
...
简易 javascript 日历
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body, ul, li {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.calendar {
margin: 10px auto;
border: 1px solid;
width: 21rem;
}
.calendar > .header {
display: flex;
justify-content: space-between;
align-items: center;
margin: .5rem;
}
.calendar > .header > .middle {
text-align: center;
}
.calendar > ul {
list-style: none;
display: flex;
margin-bottom: .5rem;
}
.calendar > ul > li {
flex-basis: 3rem;
padding: .5rem;
text-align: center;
}
.calendar > ul.week {
background-color: darkgray;
}
.calendar > ul.date {
flex-wrap: wrap;
}
.calendar > ul.date > li.active {
color: red;
}
</style>
</head>
<body>
<div class="calendar">
<div class="header">
<a class="prev" href="javascript:" title="上一月">上一月</a>
<div class="middle">
<div class="year"></div>
<div class="month"></div>
</div>
<a class="next" href="javascript:" title="下一月">下一月</a>
</div>
<ul class="week">
<li>日</li>
<li>一</li>
<li>二</li>
<li>三</li>
<li>四</li>
<li>五</li>
<li>六</li>
</ul>
<ul class="date"></ul>
</div>
<script>
var date = new Date();
function calendar() {
var year = date.getFullYear(),
month = date.getMonth(),
week = date.getDay(),
day = date.getDate(),
monthStr = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'][month],
weekDays = new Date(year, month, 1).getDay(),
days = new Date(year, month + 1, 0).getDate();
// 插入年
document.getElementsByClassName('year')[0].innerHTML = year;
// 插入月
document.getElementsByClassName('month')[0].innerHTML = monthStr;
// 插入日
var dateStr = '', style;
for (var i = 0; i < weekDays; i++) dateStr += `<li></li>`;
for (var i = 1; i <= days; i++) {
style = '';
if (i === new Date().getDate() && year === new Date().getFullYear() && month === new Date().getMonth()) {
style = ' class="active"';
}
dateStr += `<li${style}>${i}</li>`;
}
document.getElementsByClassName('date')[0].innerHTML = dateStr;
}
window.onload = calendar;
document.getElementsByClassName('prev')[0].onclick = function () {
date.setMonth(date.getMonth() - 1);
calendar();
}
document.getElementsByClassName('next')[0].onclick = function () {
date.setMonth(date.getMonth() + 1);
calendar();
}
</script>
</body>
</html>
下一篇: echarts移动端的适配思路
推荐阅读
-
诘屈聱牙之javascript中国象棋_javascript技巧
-
Javascript下的urlencode编码解码方法附decodeURIComponent
-
js实现右下角可关闭最小化div(可用于展示推荐内容)_javascript技巧
-
JavaScript 判断某个对象是Object还是一个Array
-
javascript - jq 如何显示出来下拉框value的值
-
javascript require.js的具体使用方法
-
通过JavaScript或PHP检测Android设备
-
javascript基础课程之运算符定义用法详解
-
使用UglifyJS合并/压缩JavaScript的方法_基础知识
-
javascript+css3开发打气球小游戏完整代码