如图:
简单、易懂、写着玩儿的……
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="myDate"></div>
<script>
(function(id, options){
this._date = new Date()
this.dateObj = {
_year: this._date.getFullYear(),
_month: this._date.getMonth() + 1,
_date: this._date.getDate(),
_hour: this._date.getHours(),
_minutes: this._date.getMinutes(),
_seconds: this._date.getSeconds(),
}
this.config = {
width: options.width ? options.width : 320,
height: options.height ? options.height : 240,
sundayColor: options.sundayColor ? options.sundayColor : '#F7A597',
SaterdayColor: options.SaterdayColor ? options.SaterdayColor : '#D0F7CC',
curColor: options.curColor ? options.curColor : '#f00',
}
// 本月多少天
this.calcMonthDays = function(){
return new Date(this.dateObj._year, this.dateObj._month, 0).getDate()
}
// 1号星期几
this.calcDay1Week = function(){
return new Date(this.dateObj._year + '-' + this.dateObj._month + '-' + 1).getDay()
}
// 生成日历表头, 周日到周六
this.createTableTitle = function(){
var week = ['日', '一', '二', '三', '四', '五', '六'], nullTd = [], i
for(i=0; i<week.length; i++){
nullTd.push('<th>' + week[i] + '</th>')
}
return nullTd
}
// 生成空表格
this.createNullTd = function(){
var nullTd = this.createTableTitle(), i
for(i=0; i<this.calcDay1Week(); i++){
nullTd.push('<td></td>')
}
return nullTd
}
// 生成日期表体, 1号到月底
this.createTableBodyTr = function(){
var nullTd = this.createNullTd(), totalDays = this.calcMonthDays() + this.calcDay1Week(), i
for(i=1; i<=this.calcMonthDays(); i++){
if (this.dateObj._date == i){
nullTd.push('<td style="color:' + this.config.curColor + '">' + i + '</td>')
}else{
nullTd.push('<td>' + i + '</td>')
}
}
console.log(totalDays)
if (totalDays% 7 != 0){
for(var i=0; i<(7 - totalDays % 7); i++){
nullTd.push('<td></td>')
}
}
return nullTd
}
// 渲染表格
this.render = function(id){
var myDate = document.getElementById(id),
nullTd = this.createTableBodyTr()
var table, tableBegin = '<table style="width:' + this.config.width + 'px;height:' + this.config.height +'px;text-align:center">', tableEnd = '</table>', tr = '<tr>'
for(var i=0; i<nullTd.length; i++){
if (i%7 == 0 && i>1){
tr += '</tr><tr>'
}
tr += nullTd[i]
}
tr += '</tr>'
table = tableBegin + tr + tableEnd
myDate.innerHTML = table
}
this.render(id)
console.log(options)
})('myDate', {width:320, height:240})
</script>
</body>
</html>
非常简单,也易于修改,有兴趣的可以加上上一个月,下一个月等等
标签:function,写个,JavaScript,var,._,date,nullTd,options,日历 From: https://blog.csdn.net/zzjnlwb/article/details/136918024