Ultimamente, tenho apressado para projetos. O projeto está finalmente em um estado estável agora, apenas revisões. Como programador de fundo, sou muito difícil. Eu tenho que escrever tudo, desde a web até a interface móvel, o que é muitas coisas. . . Finalmente fiquei ocioso nesses dois dias. Eu olhei algumas funções sobre as datas do JS e de repente pensei no controle do calendário. Então eu tentei escrever um. Como programador de fundo, sou limitado no meu nível. Vamos tomar uma atitude de aprendizado e olhar para o exemplo que escrevi. . .
Primeiro, uma função de data comumente usada: data (ano, mês, dia)
A cópia do código é a seguinte:
var date = new Date ();
Obtenha ano
A cópia do código é a seguinte:
var ano = this.date.getlyear ();
Obtenha mês, aqui está o índice mensal, então você precisa de +1
A cópia do código é a seguinte:
var mês = this.date.getmonth ()+1;
Que dia é a data de aquisição
A cópia do código é a seguinte:
var dia = this.date.getdate ();
Pegue o dia da semana, retorne 0. Domingo 1. Segunda -feira 2. Terça -feira 3. Quarta -feira 4. Quinta
A cópia do código é a seguinte:
var semana = this.date.getday ();
Obtenha que dia da semana é naquele mês
A cópia do código é a seguinte:
var getWeekday = função (ano, mês, dia) {
var data = nova data (ano, mês, dia);
Data de retorno.getday ();
}
var weekStart = getWeekday (this.year, this.month-1, 1)
Obtenha o número de dias no mês
A cópia do código é a seguinte:
var getMonthDays = função (ano, mês) {
var data = nova data (ano, mês, 0);
Data de retorno.getDate ();
}
var mesesdays = this.getmonthDays (this.year, this.month);
Ok, usamos apenas tantos parâmetros. A seguir, são apresentadas algumas operações e julgamentos sobre a data correspondente à semana, rótulos dinâmicos de splicing. Vamos postar diretamente o exemplo que escrevi:
A cópia do código é a seguinte:
<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 calendário = function () {
this.init.Apply (isto, argumentos);
}
Calender.prototype = {
Init: function (contêiner, opções) {
this.date = new Date ();
this.year = this.date.getlyear ();
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 (contêiner);
this.options = options! = NULL? Opções: {
fronteira: '1px verde sólido',
Largura: '400px',
Altura: '200px',
BackgroundColor: 'Lightgrey',
fontcolor: 'azul'
}
},
GetMonthDays: function (ano, mês) {
var data = nova data (ano, mês, 0);
Data de retorno.getDate ();
},
getWeekday: function (ano, mês, dia) {
var data = nova data (ano, mês, dia);
Data de retorno.getday ();
},
View: function () {
var tableSt = '<table>';
TableSt+= '<tr> <td colspan = "3"> </td> <td> ano:'+this.year+'</td> <td colspan = "3"> mês:' this.month+'</td> </tr>';
TableSt+= '<tr> <td> dia </td> <td> um </td> <td> dois </td> <td> três </w TD> <td> cinco </w/td> <td> seis </td> </tr>;
var índice = 1;
// julga onde o primeiro dia de cada mês é
var style = '';
if (this.weekstart <7)
{
TableSt+= '<tr>';
for (var i = 0; i <this.weekstart; i ++) {
TableSt+= '<Td> </td>';
};
for (var i = 0; i <7-this.Weekstart; i ++) {
style = this.day == (i+1)? "Coro de fundo: verde;": "";
índice ++;
Tablest+= '<td style = "'+style+'" val ='+(this.year+'-'+this.month+'-'+(i+1))+'>'+(i+1)+'</td>';
};
TableSt+= '</tr>';
}
/// a posição correspondente aos dias restantes
// julga linhas inteiras e corresponde às posições correspondentes
var restante
var row = math.floor (restos de restos%7 == 0? Restantes/7: ((restos de remanescente/7) +1)));
var count = math.floor (restos de restos/7);
for (var i = 0; i <contagem; i ++) {
TableSt+= '<tr>';
for (var k = 0; k <7; k ++) {
style = this.day == (índice+k)? "Coro de fundo: verde;": "";
Tablest+= '<td style = "'+style+'" val ='+(this.year+'-'+this.month+'-'+(index+k))+'>';
TableSt+= índice+k;
TableSt+= '</td>';
};
TableSt+= '</tr>';
índice+= 7;
};
// A posição correspondente dos últimos dias restantes (não pode preencher naqueles dias de uma semana)
var restante = this.monthDays- (índice-1);
TableSt+= '<tr>';
for (var i = 0; i <permanecemcols; i ++) {
style = this.day == Índice? "Coro de fundo: verde;": "";
Tablest+= '<td style = "'+style+'" val ='+(this.year+'-'+this.month+'-'+(index))+'>';
TableSt+= Índice;
TableSt+= '</td>';
índice ++;
};
TableSt+= '</tr>';
TableSt+= '</tabela>';
retornar tablests;
},
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 = 'ponteiro';
calendardiv.style.backgroundColor = this.options.backgroundColor;
// calendardiv.style.color = this.options.fontcolor;
calendardiv.style.color = 'vermelho';
calendardiv.OnClick = function (e) {
var evt = e || window.event;
var no destino = evt.srcelement || evt.target;
if (Target && Target.getAttribute ('val'))
{
alert (Target.getAttribute ('val'));
}
}
var tableSt = this.View ();
this.tablestr = tablest;
calendardiv.innerhtml = tablest;
var div = document.createElement ('div');
div.style.width = 'Auto';
div.style.Height = 'Auto';
Div.AppendChild (CalenderDiv);
/// Page Turn Div
var pagerdiv = document.createElement ('div');
Pagerdiv.style.width = 'Auto';
Pagerdiv.style.Height = 'Auto';
var que = this;
/// Redefinir parâmetros
var resetpara = função (ano, mês, dia) {
that.date = nova data (ano, mês, dia);
that.year = that.date.getlyear ();
that.month = that.date.getMonth ()+1;
that.day = that.date.getdate ();
that.week = that.date.getday ();
that.weekstart = that.getweekday (that.year, that.month-1, 1);
that.monthDays = that.getmonthDays (that.year, that.month);
}
// página anterior
var preBtn = document.createElement ('input');
prebtn.type = 'botão';
prebtn.value = '<';
prebtn.onClick = function () {
that.Containerdiv.RemoveChild (div);
resetpara (that.year, that.month-2, that.day);
that.render ();
}
// Próxima página
var nextBtn = document.createElement ('input');
nextbtn.type = 'botão';
nextbtn.value = '>';
nextbtn.OnClick = function () {
that.Containerdiv.RemoveChild (div);
resetpara (that.year, that.month, that.day);
that.render ();
}
Pagerdiv.appendChild (prebtn);
Pagerdiv.appendChild (NextBtn);
Div.AppendChild (PAGERDIV);
var DropDiv = document.createElement ('div');
var DropDivstr = '';
// Selecione o ano
DropDivstr+= '<select id = "ddlyear">';
for (var i = 1900; i <= 2100; i ++) {
DropDivstr+=
i == that.year
? '<opção value = "'+i+'" selected = "true">'+i+'</ppthion>'
: '<opção value = "'+i+'">'+i+'</pption>';
};
DropDivstr+= '</leclect>';
// Selecione o mês
DropDivstr+= '<SELECT ID = "DDLMONTH">';
for (var i = 1; i <= 12; i ++) {
DropDivstr+=
i == that.month
? '<opção value = "'+i+'" selected = "true">'+i+'</ppthion>'
: '<opção value = "'+i+'">'+i+'</pption>';
};
DropDivstr+= '</leclect>';
DropDiv.innerhtml = DropDivstr;
Div.AppendChild (DropDiv);
that.containerdiv.appendChild (div);
/// vincula o evento que seleciona ano e mês
var ddlChange = function () {
var ddlyear = document.getElementById ('ddlyear');
var ddlmonth = document.getElementById ('ddlmonth');
var anoIndex = ddlyear.SelectedIndex;
var ano = ddlyear.options [ano -index] .Value;
var MonthIndex = ddlmonth.SelectedIndex;
var mês = ddlMonth.Options [MonthIndex] .Value;
that.Containerdiv.RemoveChild (div);
resetpara (ano, mês-1, that.day);
that.render ();
}
ddlyear.onchange = function () {
ddlchange ();
}
ddlmonth.onchange = function () {
ddlchange ();
}
}
}
VAR calendário = novo calendário ('dvTest', {
fronteira: '1px verde sólido',
Largura: '400px',
Altura: '200px',
BackgroundColor: ''
}
);
calendário.render ();
}
</script>
</head>
<Body>
<div id = "dvTest"> </div>
</body>
</html>
O código foi alterado novamente e a tabela da visualização é substituída por uma div, a fim de resolver o problema somente leitura da tabela da IE da IE. Além disso, são adicionadas opções para configurabilidade.
O código acima tem uma explicação simples, a função é a mais básica e, se você o fizer mais profundo, poderá expandi-la.