Recientemente, miré algunas funciones sobre las fechas de JS y de repente pensé en el control del calendario. Así que intenté escribir uno. Como programador de fondo, estoy limitado en mi nivel. Tomemos una actitud de aprendizaje y echemos un vistazo al ejemplo que escribí. ¡Aprendamos juntos para avanzar!
Primero, una función de fecha de uso común:
Fecha (año, mes, día)
var fecha = nueva fecha ();
Obtener el año
var año = this.date.getblyear ();
Obtener mes, aquí está el índice mensual para que necesite +1
var mes = this.Date.getMonth ()+1;
¿Qué día es la fecha de adquisición?
var day = this.date.getDate ();
Obtenga el día de la semana, regrese 0. Domingo 1. Lunes 2. Martes 3. Miércoles 4. Jueves 5. Viernes 6. Sábado
var semana = this.date.getday ();
Obtenga qué día de la semana es ese mes
var getweekday = function (año, mes, día) {var fecha = nueva fecha (año, mes, día); Fecha de devolución.getday (); } var WeekStart = Getweekday (this.Year, this.Month-1, 1)Obtenga la cantidad de días en el mes
var getMonthdays = function (año, mes) {var fecha = nueva fecha (año, mes, 0); fecha de retorno.getDate (); } var mes mes de mes.Bien, solo hemos usado tantos parámetros. Lo siguiente es en realidad algunas operaciones y juicios sobre la fecha correspondiente a la semana, las etiquetas de empalme dinámicas. Publicemos directamente el ejemplo que escribí:
Imagen de reproducción:
<html> <meta http-equiv = "content-type" content = "text/html; charset = utf-8"> <head> <style type = "text/css"> td {text-align: center;} </style> <script type = "text/javaScript"> window.onload = function () {var calender = function () this.init.apply (this, argumentos); } Calender.prototype = {init: function (contenedor, opciones) {this.date = new Date (); this.year = this.Date.getTlyAr (); this.month = this.Date.getMonth ()+1; this.day = this.date.getDate (); this.week = this.date.getday (); this.weekstart = this.getweekday (this.year, this.month-1, 1); this.Monthdays = this.getMonthdays (this.year, this.month); this.containerDiv = document.getElementById (contenedor); this.options = options! = NULL? Opciones: {borde: '1px sólido verde', ancho: '400px', altura: '200px', backgroundColor: 'lightgrey', fontcolor: 'blue'}}, getMonthdays: función (año, mes) {Var fecha = nueva fecha (año, mes, 0); fecha de retorno.getDate (); }, Getweekday: function (año, mes, día) {var fecha = nueva fecha (año, mes, día); Fecha de devolución.getday (); }, Ver: function () {var tablests = '<table>'; TABLEST+= '<tr> <td colspan = "3"> </td> <td> año:'+this.year+'</td> <td colspan = "3"> mes:'+this.month+'</td> </tr>'; TABLEST+= '<tr> <TD> DAY </td> <td> two </td> <td> cuatro </td> <td> cinco </td> <td> Six </td> </tr>'; índice var = 1; // juzga donde el primer día de cada mes es var style = ''; if (this.weekstart <7) {tablests+= '<tr>'; for (var i = 0; i <this.weekstart; i ++) {tablests+= '<td> </td>'; }; para (var i = 0; i <7-This.weekStart; i ++) {style = this.day == (i+1)? "Color de fondo: verde;": ""; índice ++; tablests+= '<td style = "'+style+'" val ='+(this.year+'-'+this.month+'-'+(i+1))+'>'+(i+1)+'</td>'; }; tablests+= '</tr>'; } /// La posición correspondiente a los días restantes // juzga la fila entera y corresponde a la posición correspondiente var permanece días = this.Monthdays- (7-this.weekStart); var fila = math.floor (RTAILDAYS%7 == 0? RTAILDAYS/7: ((RTAI LAYAS/7) +1)); var count = Math.Floor (RTIESSDAYS/7); for (var i = 0; i <count; i ++) {tablests+= '<tr>'; para (var k = 0; k <7; k ++) {style = this.day == (índice+k)? "Color de fondo: verde;": ""; TABLEST+= '<td style = "'+style+'" "val ='+(this.year+'-'+this.month+'-'+(index+k)+'>'; tablestr+= index+k; tablests+= '' </td> ';}; tablests+=' '</tr>'; índice+= 7;//la posición correspondiente a los últimos días (los días de la última vez (los días de la semana no se pueden rellenar los días (los días de la semana que no pueden ser rellenados (los días no se pueden rellenar) permanente = this.monthays- (index-1); tablests+= índice; tablests+= '</td>'; índice ++; }; tablests+= '</tr>'; tablests+= '</table>'; Vuelve tablos; }, Render: function () {var calendARDIV = document.createElement ('div'); calendardiv.style.border = this.options.border; calendardiv.style.width = this.options.width; calendardiv.style.height = this.options.Height; calendardiv.style.cursor = 'Pointer'; calendARDIV.style.backgroundColor = this.options.backgroundcolor; // calendardiv.style.color = this.options.fontcolor; calendARDIV.style.color = 'rojo'; calendARDIV.OnClick = function (e) {var evt = e || window.event; var Target = EVT.SrCelement || evt.target; if (target && target.getAttribute ('val')) {alert (target.getAttribute ('val')); }} var tablests = this.view (); this.tablestr = tablestr; calendARDIV.InnerHTML = TABLESTR; var div = document.createElement ('div'); div.style.width = 'Auto'; div.style.height = 'Auto'; div.appendchild (CalenderDiv); /// Página Turn Div Var PagerDiv = Document.CreateElement ('div'); PagerDiv.Style.Width = 'Auto'; Pagerdiv.style.height = 'Auto'; var que = esto; /// Restablecer el parámetro var reetpara = function (año, mes, día) {that.date = new Date (año, mes, día); que.Year = that.date.getblyear (); eso.month = that.date.getMonth ()+1; that.day = that.date.getDate (); that.week = that.date.getday (); que.weekstart = that.getweekday (que.Year, que.Month-1, 1); eso. Monthdays = que.getMonthdays (que. } // página anterior var preBtn = document.createElement ('input'); prebtn.type = 'botón'; prebtn.value = '<'; preBtn.OnClick = function () {that.containerDiv.remoVechild (div); resetpara (que.Year, que.Month-2, que.day); que.render (); } // página siguiente var nextbtn = document.createElement ('input'); nextbtn.type = 'botón'; nextbtn.value = '>'; nextBtn.OnClick = function () {that.containerDiv.removechild (div); resetpara (que.Year, eso. Month, que.day); que.render (); } PagerDiv.AppendChild (preBTN); PagerDiv.AppendChild (NextBtn); div.appendchild (PagerDiv); var dropDiv = document.createElement ('div'); var dropDivStr = ''; // Seleccionar año dropDivStr+= '<select id = "ddlyear">'; para (var i = 1900; i <= 2100; i ++) {dropDivStr+= i == that.year? '<option value = "'+i+'" selected = "true">'+i+'</option>': '<opcion value = "'+i+'">'+i+'</option>; }; dropDivStr+= '</select>'; // seleccionar mes dropDivStr+= '<select id = "ddlmonth">'; for (var i = 1; i <= 12; i ++) {dropDivStr+= i == that.month? '<option value = "'+i+'" selected = "true">'+i+'</option>': '<opcion value = "'+i+'">'+i+'</option>'; }; dropDivStr+= '</select>'; dropdiv.innerhtml = dropDivStr; div.appendchild (dropdiv); que.containerdiv.appendchild (div); /// Atrae el evento que selecciona el año y el mes var ddlChange = function () {var ddlyear = document.getElementById ('ddlyear'); var ddlmonth = document.getElementById ('ddlmonth'); var YearIndex = ddlyear.selectedIndex; var año = ddlyear.options [YearIndex] .Value; var mesindex = ddlmonth.selectedIndex; var mes = ddlmonth.options [mesindex] .value; que.containerdiv.removechild (div); Resetpara (año, mes-1, th.day); que.render (); } ddlyear.onchange = function () {ddlchange (); } ddlmonth.onchange = function () {ddlchange (); }}} var calendar = new Calender ('dvtest', {border: '1px sólido verde', ancho: '400px', altura: '200px', backgroundcolor: ''}); calendario.render (); } </script> </head> <body> <div id = "dvtest"> </div> </body> </html>El código se ha cambiado nuevamente y la tabla de la vista se reemplaza con un DIV, para resolver el problema de solo lectura de TableInnerHTML de IE. Además, se agregan opciones para la configuración.
El código anterior tiene una explicación simple, y las funciones son las más básicas. Si lo hace en profundidad, puede expandirlo. Espero que este artículo pueda darte algo de inspiración.