<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
#header {
position: relative;
height: 30px;
}
#header div {
position: absolute;
width: 60px;
height: 30px;
line-height: 30px;
text-align: center;
color: #000;
border: 1px solid #f7f7f7;
box-sizing: border-box;
top: 0;
}
#header div:nth-of-type(1) {
left: 0;
}
#header div:nth-of-type(2) {
left: 60px;
}
#header div:nth-of-type(3) {
left: 120px;
}
#header div:nth-of-type(4) {
left: 180px;
}
#header div:nth-of-type(5) {
left: 240px;
}
#header div:nth-of-type(6) {
left: 300px;
}
#header div:nth-of-type(7) {
left: 360px;
}
#root {
position: relative;
width: 420px;
}
#root div {
position: absolute;
width: 60px;
height: 30px;
border: 1px solid #f7f7f7;
box-sizing: border-box;
top: 0;
left: 0;
text-align: center;
line-height: 30px;
}
</style>
</head>
<body>
<div id="header">
<div>周日</div>
<div>周一</div>
<div>周二</div>
<div>周三</div>
<div>周四</div>
<div>周五</div>
<div>周六</div>
</div>
<div id="root"></div>
<script>
// 获取当前日期对应当前月份内所有日期的信息
Date.prototype.getNowMonthData = function (e) {
const { origin = [0,0], offsetX = 0, offsetY = 0 } = e;
const year = this.getFullYear();
const month = this.getMonth() + 1;
const day = this.getDay();
const monthTotalDays = new Date(year, month, 0).getDate();
const data = Array.from({ length: monthTotalDays }, function (v, i) {
const newDate = new Date(year, month - 1, i + 1);
const day = newDate.getDay();
const date = newDate.getDate();
const monthWeek = Math.ceil((date + 6 - day) / 7);
return {
index: i + 1,
date,
year,
month,
day,
monthWeek: monthWeek,
info: `${year}-${month}-${i + 1},周${day || "日"},第${monthWeek}周`,
coord: [
origin[0] + day * offsetX,
origin[1] + (monthWeek - 1) * offsetY,
],
};
});
return data
};
const origin = [0, 0]; // 原点坐标
const offsetX = 60; // 每日的间距横偏移量
const offsetY = 30; // 每日的间距纵偏移量
const date = new Date('2022-01-01');
const data = date.getNowMonthData({
origin,
offsetX,
offsetY,
});
const root = document.getElementById("root");
let dom = document.createDocumentFragment();
data.forEach(function (item) {
const domItem = document.createElement("div");
domItem.setAttribute(
"style",
`left:${item.coord[0]}px;top: ${item.coord[1]}px`
);
domItem.innerHTML = `${item.date}号`;
dom.appendChild(domItem);
});
root.appendChild(dom);
</script>
</body>
</html>
效果图: