9.6腾讯前端日历题目
HTML部分
<div id="jsContainer"> <table class="calendar"> </table> </div>
CSS部分
table.calendar {
font-size: 14px;
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
table.calendar th{
background: #f5f5f5;
color: #999;
}
table.calendar th,
table.calendar td {
border: 1px solid #e1e1e1;
padding: 0;
height: 32px;
line-height: 32px;
text-align: center;
}
table.calendar td.current{
background: #1890ff;
color: #fff;
}
table.calendar th.pre,
table.calendar th.next{
color: #1890ff;
cursor: pointer;
}
table.calendar th.date{
color: #000;
}JS部分
function Calendar(container, year, month) {
this.year = year;
this.month = month;
this.html = html;
this.el = document.getElementsByTagName('table')[0]; // TODO
if (!el) return;
this.el.className = 'calendar';
this.el.innerHTML = this.html();
container.appendChild(this.el);
this.el.addEventListener('click', event => {
var el = event.target;
var isPre = el.classList.contains('pre');
var isNext = el.classList.contains('next');
if (!isPre && !isNext) return;
if (isPre) {
// TODO
if (this.month === 1) {
this.year -= 1;
this.month = 12;
} else {
this.month -= 1;
}
} else {
// TODO
if (this.month === 12) {
this.year += 1;
this.month = 1;
} else {
this.month += 1;
}
}
this.el.innerHTML = this.html();
});
function html() {
var date = new Date();
var year = +this.year || 0;
var month = (+this.month || 0) - 1;
// TODO
var curr = -1; // 用来确认是否为当天
if (date.getFullYear() === year && date.getMonth() === month) {
curr = date.getDate();
}
var firstdate = new Date(`${year}-${this.month}`); // 找到月初的时间对象,可以通过月初是星期几来计算1号前面有多少个空值(-1)
var firstday = firstdate.getDay();
var arr = [];
// 1号前面填充 -1;
if (!firstday) {
arr.push(...(new Array(6).fill(-1)));
} else {
for (var i = 1; i < firstday; i++) {
arr.push(-1);
}
}
// 1 号到月底
var y = year;
var m = month; // 0 ~ 11
if (month === 11) {
y = year + 1;
m = 1;
} else {
// 之所以加2是因为下面要计算月底后面有多少个空值,由于存在大小月和2月的不同,所以直接获取到下一个月初的时间,减去一天的时间就是本月月底的时间
m += 2;
}
var temp = new Date(`${y}-${m}`).getTime();
var time = 86400000
var endDate = new Date(temp-time); // 得到月底的时间对象
var enddays = endDate.getDate();
var endday = endDate.getDay();
for (var i = 1; i <= enddays; i++) { // 这里是 1号到月底的日期
arr.push(i);
}
// 月底之后还有多少个 -1;
if (endday !== 0) { // 月底之后的空值数量
arr.push(...(new Array(7-endday).fill(-1)))
}
// 到这里为止,当前月份的所有的数字都保存在数组当中了,包括-1在内
var str = ``;
var s = '';
for (var k = 0; k < arr.length; k++) {
s += `<td ${curr !== -1 && curr === arr[k] ? 'class="current"': ''}>${arr[k] === -1 ? '' : arr[k]}</td>`
if ((k+1) % 7 === 0) {
str += `<tr>${s}</tr>`;
s = '';
}
}
// 下面是 table标签中的内容
var html = `
<thead>
<tr><th class="pre"><</th><th colspan="5" class="date">${year}-${this.month}</th><th class="next">></th></tr>
<tr><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th><th>日</th></tr>
</thead>
<tbody>
${str}
</tbody>
`;
return html;
}
}
Calendar(document.getElementById('jsContainer'), 2020, 9) // 测试用例本地测试没问题,不知道为啥牛客通过不了,有的地方写的很烂抱歉!
#笔试题目##腾讯#