js自定义日历组件
2021-04-01 13:27
标签:改变 device isp charset lex cto 插件 Oday tip js日历插件 实现思路:获取每个月的第一天是星期几,然后把前面的天数填充为空,在获取每个月有多少天,循环填充,判断并给给当前时间添加单独样式,点击上一月,和下一月时改变月份。 js自定义日历组件 标签:改变 device isp charset lex cto 插件 Oday tip 原文地址:https://www.cnblogs.com/zimengxiyu/p/12568477.htmlDOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
meta name="viewport" content="width=device-width, initial-scale=1.0">
title>Documenttitle>
style>
* {
margin: 0;
padding: 0;
}
body {
background: #2c3e50;
}
.calendar {
width: 400px;
margin: 50px auto;
}
.calendar-tip {
font-size: 16px;
text-align: center;
color: #fff;
}
.prev {
float: left;
cursor: pointer;
}
.next {
float: right;
cursor: pointer;
}
.calendar-month {
text-align: center;
margin: 10px 0;
color: #fff;
}
ul {
list-style: none;
display: flex;
}
li {
width: 57px;
text-align: center;
height: 55px;
line-height: 55px;
font-size: 16px;
color: #fff;
}
.calendar-day {
display: flex;
}
.calendar-day span {
flex: 1;
color: #fff;
text-align: center;
height: 40px;
line-height: 40px;
}
.calendar-data {
display: flex;
flex-wrap: wrap;
}
li {
width: 57px;
cursor: pointer;
}
li:hover {
background: #2d3436;
}
.calendar-data .on {
color: #d63031;
}
style>
head>
body>
div class="calendar">
div class="calendar-tip">
span class="prev">上一月span>
em id="year">2022年em>
span class="next">下一月span>
div>
div class="calendar-month">五月div>
div class="calendar-day">
span>日span>
span>一span>
span>二span>
span>三span>
span>四span>
span>五span>
span>六span>
div>
ul class="calendar-data">
li>1li>
li>1li>
li>1li>
li>1li>
li>1li>
li>1li>
li>1li>
ul>
div>
script>
var date = new Date();
var year = document.querySelector("#year");
var month = document.querySelector(".calendar-month");
var calendarData = document.querySelector(".calendar-data");
var prev = document.querySelector(".prev");
var next = document.querySelector(".next");
var monthArr = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"];
var y, html, day, today;
calendar();
function calendar() {
y = date.getFullYear();
year.innerHTML = y + "年";
m = date.getMonth();
month.innerHTML = monthArr[m];
day = new Date(y, m, 1).getDay(); //获取每个月第一天是周几
d = new Date(y, m + 1, -1).getDate() + 1; //获取多少天
html = "";
//把每个月第一天之前的时间填充为空
for (var i = 1; i day; i++) {
html += "