He estado apresurando por proyectos últimamente. El proyecto finalmente está en un estado estable ahora, solo revisiones. Como programador de fondo, soy muy duro. Tengo que escribir todo, desde la web hasta la interfaz móvil, que son muchas cosas. . . Finalmente puse inactivo estos dos días. 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 veamos el ejemplo que escribí. . .
Primero, una función de fecha de uso común: fecha (año, mes, día)
La copia del código es la siguiente:
var fecha = nueva fecha ();
Obtener el año
La copia del código es la siguiente:
var año = this.date.getblyear ();
Obtener mes, aquí está el índice mensual para que necesite +1
La copia del código es la siguiente:
var mes = this.Date.getMonth ()+1;
¿Qué día es la fecha de adquisición?
La copia del código es la siguiente:
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
La copia del código es la siguiente:
var semana = this.date.getday ();
Obtenga qué día de la semana es ese mes
La copia del código es la siguiente:
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
La copia del código es la siguiente:
var getMonthdays = function (año, mes) {
VAR fecha = nueva fecha (año, mes, 0);
fecha de retorno.getDate ();
}
var meses días = this.getMonthdays (this.Year, this.Month);
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í:
La copia del código es la siguiente:
<html>
<meta http-equiv = "content-type" content = "text/html; charset = utf-8">
<Evista>
<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 de verde sólido',
Ancho: '400px',
Altura: '200px',
backgroundcolor: 'lightgrey',
FontColor: 'Azul'
}
},
getMonthdays: function (año, mes) {
VAR fecha = nueva fecha (año, mes, 0);
fecha de retorno.getDate ();
},
getweekday: función (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> one </td> <td> two </td> <td> tres </ tw </td> <td> cinco </tw </td> <td> Six </td> </tr>';
índice var = 1;
// juzga dónde está el primer día de cada mes
Var style = '';
if (this.weekstart <7)
{
tablests+= '<tr>';
para (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
// Juez de filas enteras y corresponde a las posiciones correspondientes
Var queda día = this.Monthdays- (7-this.weekStart);
var fila = Math.floor (RTAILDAYS%7 == 0? RTAILDAYS/7: ((RTAITAYS/7) +1)));
var count = Math.Floor (RTIESSDAYS/7);
para (var i = 0; i <count; i ++) {
tablests+= '<tr>';
para (var k = 0; k <7; k ++) {
style = this.day == (índice+k)? "Color de fondo: verde;": "";
tablests+= '<td style = "'+style+'" val ='+(this.year+'-'+this.month+'-'+(index+k))+'>';
tablestas+= índice+k;
tablests+= '</td>';
};
tablests+= '</tr>';
índice+= 7;
};
// La posición correspondiente de los últimos días restantes (no se puede llenar esos días de una semana)
var reTiCols = this.Monthdays- (index-1);
tablests+= '<tr>';
para (var i = 0; i <permanente; i ++) {
style = this.day == índice? "Color de fondo: verde;": "";
TABLEST+= '<td style = "'+style+'" val ='+(this.year+'-'+this.month+'-'+(index))+'>';
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'))
{
alerta (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 los parámetros
var reetpara = function (año, mes, día) {
que.date = nueva fecha (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 ('entrada');
prebtn.type = 'botón';
prebtn.value = '<';
preBtn.OnClick = functer () {
que.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 () {
que.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 == eso.
? '<option value = "'+i+'" selected = "true">'+i+'</option>'
: '<option value = "'+i+'">'+i+'</option>';
};
dropDivStr+= '</select>';
// Seleccionar mes
dropDivStr+= '<select id = "ddlmonth">';
para (var i = 1; i <= 12; i ++) {
dropDivstr+=
i == eso.
? '<option value = "'+i+'" selected = "true">'+i+'</option>'
: '<option value = "'+i+'">'+i+'</option>';
};
dropDivStr+= '</select>';
dropdiv.innerhtml = dropDivStr;
div.appendchild (dropdiv);
que.containerdiv.appendchild (div);
/// vincule el evento que selecciona año y 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, ese día);
que.render ();
}
ddlyear.onchange = function () {
ddlchange ();
}
ddlmonth.onchange = function () {
ddlchange ();
}
}
}
var calendar = new Calender ('dvtest', {
borde: '1px de verde sólido',
Ancho: '400px',
Altura: '200px',
backgroundcolor: ''
}
);
calendario.render ();
}
</script>
</ablo>
<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, la función es la más básica, y si lo hace más en profundidad, puede expandirla.