Classificação simples de mesa
Você pode clicar duas vezes para editar regras editadas personalizadas
Colunas arrastáveis para substituição da coluna
Empurre as fronteiras para escalar as larguras da coluna
A cópia do código é a seguinte:
<! Doctype html public "-// w3c // dtd xhtml 1.0 transitional // pt" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-bransitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "content-type" content = "text /html; charset = gb2312" />
<title> tabela </title>
</head>
<style type = "text/css">
corpo {tamanho da fonte: 12px}
#tab {border-colapso: colapso;}
.edit {altura: 16px; largura: 98%; Background-Color:#eff7ff; tamanho de fonte: 12px; Fronteira: 0px;}
#tab thead td {background: url (http://images.cnblogs.com/cnblogs_com/wtcsy/192373/r_t.bmp); cor:#183c94; word-break: break-all}
#tab tbody td {Overflow: hidden; word-break: break-all;}
#tab td {borda: 1px sólido #Cecfce; altura: 20px; altura da linha: 20px; alinhamento vertical: meio; }
#tab td.tc {text-align: Center;}
.div {width: 10px; altura: 6px; fronteira: 1px Solid #999999; Background-Color: #fffff; Posição: Absoluto; Exibição: Nenhum;}
.line {width: 2px; Background-Color:#999999; Posição: Absoluto; Exibição: Nenhum}
.dr {altura: 100%; largura: 2px; fundo: #cecfce; float: direita; margem-direita: -1px; cursor: sw-resize}
.r {float: direita;}
.l {float: esquerda;}
#tab thead td.ThOver {Background-Image: url (http://album.hi.csdn.net/app_uploads/wtcsy/20081126/000054336.p.gif); background-repeat: repetição-x;}
</style>
<Body>
<tabela id = "tab" CellPacing = "1" CellPadding = "0">
<head>
<tr>
<tdclass = "tc"> <pan> id </span> <div> </div> </td>
<tdclass = "tc"> <pan> selecione </span> <div> </div> </td>
<td> <pan> nome </span> <div> </div> </td>
<td> <pan> aniversário </span> <div> </div> </td>
<td> <pan> observações </span> <div> </div> </td>
</tr>
</head>
<Tbody>
<tr>
<Td> 1 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<Td> missy </td>
<Td> 1982-05-27 </td>
<td> xícaras, todas as xícaras </td>
</tr>
<tr>
<Td> 3 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<td> li si </td>
<Td> 1983-06-27 </td>
<Td> Sim, eu tenho boas habilidades em Warcraft </td>
</tr>
<tr>
<Td> 2 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<td> wang wu </td>
<Td> 1987-05-27 </td>
<Td> A lâmina do príncipe persa não é ruim </td>
</tr>
<tr>
<Td> 4 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<td> zhao liu </td>
<Td> 1988-05-27 </td>
<Td> Meu nome é Zhao Liu </td>
</tr>
<tr>
<Td> 5 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<td> zhu ba </td>
<Td> 1984-05-27 </td>
<td> varrer e vá para a cama </td>
</tr>
<tr>
<Td> 6 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<td> asdorf </td>
<Td> 1984-06-27 </td>
<td> asdorf quarto escuro com luzes </td>
</tr>
<tr>
<Td> 7 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<td> cop </td>
<Td> 1984-06-27 </td>
<Td> Muitos copos </td>
</tr>
<tr>
<Td> 8 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<td> louça </td>
<Td> 1984-02-27 </td>
<Td> Muitos utensílios de mesa </td>
</tr>
<tr>
<Td> 8 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<td> Lavagem de utensílios </td>
<Td> 1984-08-27 </td>
<Td> Muitos utensílios de lavagem </td>
</tr>
<tr>
<Td> 9 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<Td> A lula está cheia de rosto </td>
<Td> 1984-12-27 </td>
<Td> 10 quase uma noite </td>
</tr>
<tr>
<Td> 10 </td>
<Td> <input type = "Caixa de seleção"> <nome de entrada = "ss" type = "radio" /> </td>
<td> cialis irmão </td>
<Td> 1984-12-21 </td>
<td> hehe </td>
</tr>
</tbody>
</tabela>
<Script Language = "JavaScript">
(função (janela, indefinida) {
window.sys = function (ua) {
var b = {
ou seja: /msie/.test(ua) &&! /opera/.test (ua),
ópera: /opera/.test(ua),
safari: /webkit/.test(ua) &&! /chrome/.test (ua),
firefox: /firefox/.test(ua),
Chrome: /chrome/.test(ua)
}, vmark = "";
para (var i em b) {
if (b [i]) {vmark = "safari" == i? "Versão": i; quebrar; }
}
B.Version = vmark && regexp ("(?:" + vmark + ") [///:] ([// d.] +)"). Teste (UA)? Regexp. $ 1: "0";
b.ie6 = b.ie && parseint (b.version, 10) == 6;
b.ie7 = b.ie && parseint (b.version, 10) == 7;
b.ie8 = b.ie && parseint (b.version, 10) == 8;
retornar b;
} (window.navigator.userragent.tolowercase ());
window.sys.ie6 && document.execCommand ("BackgroundImageCache", false, true);
janela. $ = function (id) {
retornar document.getElementById (id);
};
window.addlistener = função (elemento, e, fn) {
! Element.events && (element.events = {});
element.events [e] && (element.events [e] [addListener.guid ++] = fn) || (element.events [e] = {'0': fn});
element.AddeventListener? Element.AddeventListener (e, fn, false): element.attachevent ("on" + e, fn);
};
window.addlistener.guid = 1;
window.removelistener = function (elemento, e, fn) {
var manipuladores = element.events [e], tipo;
if (fn) {
para (digite os manipuladores)
if (manipuladores [tipo] === fn) {
Element.RemoveEventListener? Element.RemoveEventListener (E, Fn, False): Element.Detachevent ("On" + E, Fn);
excluir manipuladores [tipo];
}
}outro{
para (tipo de manipuladores) {
element.RemoveEventListener? Element.RemoveEventListener (E, Handlers [Type], False): Element.Detachevent ("On" + E, Handlers [Type]);
excluir manipuladores [tipo];
}
}
};
window.setStyle = função (e, o) {
if (typeof o == "string")
e.style.csStext = O;
outro
para (var i em o)
e.style [i] = o [i];
};
var slice = array.prototype.slice;
window.bind = function (objeto, diversão) {
var args = slice.call (argumentos) .Slice (2);
Return function () {
retornar divertido.Apply (objeto, args);
};
};
window.bindaseventListener = function (objeto, diversão, args) {
var args = slice.call (argumentos) .Slice (2);
Função de retorno (evento) {
return Fun.Apply (Object, [Event || Window.Event] .Concat (args));
}
};
// Copiar de Jq
window.extend = function () {
VAR Target = Argumentos [0] || {}, i = 1, comprimento = argumentos.Length, Deep = true, opções;
if (typeof alvo === "boolean") {
Deep = Target;
Target = argumentos [1] || {};
i = 2;
}
if (typeof Target! == "Object" && Object.prototype.toString.Call (Target)! = "[Função do objeto]"))
Target = {};
para (; i <comprimento; i ++) {
if ((opções = argumentos [i])! = nulo)
para (Var Nome in Options) {
var src = Target [nome], copy = options [nome];
if (Target === cópia)
continuar;
if (Deep && cópia && typeof cópia === "object" &&! copy.nodetype) {
Target [nome] = argumentos.Callee (Deep, src || (copy.length! = null? []: {}), copy);
}
caso contrário, se (cópia! == indefinido)
Target [nome] = cópia;
}
}
alvo de retorno;
};
window.objpos = function (o) {
var x = 0, y = 0;
do {x += o.offsetLeft; y += o.offsettop;} while ((o = o.offsetParent));
return {'x': x, 'y': y};
}
window.class = function (propriedades) {
var _class = function () {return (argumentos [0]! == null && this.initialize && typeof (this.initialize) == 'function')? this.initialize.apply (this, argumentos): this;};
_class.prototype = Propriedades;
retornar _class;
};
window.hasclass = function (elemento, classe) {
Return element.className.match (novo regexp ('(// s |^)'+className+'(// s | $)'));
};
window.addclass = function (elemento, className) {
! this.hasclass (elemento, classe) && (element.className += "" +ClassName);
}
window.removeClass = function (elemento, classe) {
hasclass (element, className) && (element.className = element.classname.replace (new regexp ('(// s |^)'+className+'(// s | $)'), ''));
}
})(janela);
var tabela = nova classe ({
Opções: {
Minwidth: 62
},
Initialize: function (guia, set) {
this.table = guia;
this.rows = []; // registra todas as referências de TR nele
this.sortcol = null; // registra qual coluna está classificando
this.inputtd = null; // registro qual TD está sendo editado
this.editconfig = {}; // Regras e dicas para editar tabelas
this.tead = tab.getElementsByTagName ('Head') [0];
this.headtds = tab.getElementsByTagName ('head') [0] .getElementsByTagName ('td'); // A coleção DOM comumente usada pode ser referenciada com uma propriedade.
this.tbodytds = tab.getElementsByTagName ('tbody') [0] .getElementsByTagName ('td');
this.Closconfig = {
on: false,
TD: NULL,
TOTD: NULL
};
this.WidthConfig = {
TD: NULL,
Nexttd: null,
x: 0,
tdwidth: 0,
NexttdWidth: 0
};
Estender (this, this.options);
// Eu não sei o motivo, se você não o definir, você vai pular aleatoriamente
(Sys.ie6 || sys.chrome) && (tab.width = tab.offsetWidth)
// grava essas caixas de seleção, o rádio é selecionado. O IE6 não se lembrará desses estados ao fazer operações de DOM.
if (sys.ie6) {
this.checkbox = {};
Var Caixas de seleção = tab.getElementsByTagName ('input'), i = 0, l = caixa de seleção.Length;
para (; i <l; i ++)
(Caixas de seleção [i] .Type == "Caixa de seleção" || Caixas de seleção [i] .Type == "Radio") &&
addListener (caixas de seleção [i], "clique", bind (this, function (elm, i) {
elm.Checked == true? (this.checkbox [i] = elm) :( exclua this.checkbox [i]);
}, caixas de seleção [i], i));
};
var i = 0, l = set.length, linhas = tab.tbodies [0] .Rows, d = document, tabtads = tab.getElementsByTagName ('td'), length = this.theadtds.length;
// entrada usada para edição
this.input = d.createElement ('input');
this.input.type = "text";
this.input.className = 'Edit';
// usado para exibir a divisão de arrastar
this.div = d.body.appendChild (d.createElement ('div'));
this.div.classname = "div";
// A linha vertical exibida ao zoom
this.Line = D.Body.AppendChild (D.CreateElement ('div'));
this.line.className = 'line';
this.line.style.top = objpos (tab) .y +"px";
// Viaje o conjunto para fazer algumas configurações
para (; i <l; i ++) {
// vincula o evento de caçador de cabeças que precisa ser classificado
addListener (this.headtds [set [i] .id], 'clique', bind (this, this.sortTable, this.headtds [set [i] .id], set [i] .Type));
// Defina a configuração necessária para a coluna para a tabela que precisa ser editada
set [i] .edit && (this.editconfig [set [i] .id] = {regra: set [i] .edit.rule, mensagem: set [i] .edit.message});
}
// Coloque todo o TR em uma matriz para classificar
for (i = 0, l = linhas.length; i <l; i ++)
this.rows [i] = linhas [i];
// viaja por todos os TDs e faça algumas configurações
for (i = 0, l = tabtads.length; i <l; i ++) {
// Ao usar o TD na cabeça, você deve usá -lo ao arrastá -lo com marcas.
i <comprimento && tabtads [i] .SetAttribute ('clos', i);
// Adicionar atributo Editar ao TD que precisa ser editado
i> = length && this.editconfig [i%length] && tabtads [i] .SetAttribute ('editar', i%comprimento);
}
// Operações de arrasto e zoom de ligação
addListener (this.tead, 'mousedown', bindaseventListener (this, this.dragorwidth));
// Ao arrastar, o registro se move para essa coluna TD
addListener (this.tead, 'mouseOver', bindaseventListener (this, this.theadHover));
//bem
addListener (this.tead, 'mouseout', bindaseventListener (this, this.teadout));
// Evento de edição de ligação determina qual tabela é editada com base em e.srcelement ou E.Target
addListener (tab, 'dblClick', bindaseventListener (this, this.edit));
// Salve o conteúdo modificado ao deixar a entrada
addListener (this.input, 'Blur', bind (this, this.Save, this.Input));
},
Sorttable: function (td, tipo) {// td é o elemento n que clicou. Qual coluna é do tipo de classificação. Que tipo é a classificação.
var fragment = document.createCumentFragment (), span = td.getElementsByTagName ('span') [0], str = span.innerhtml;
if (td === this.sortcol) {
this.Rows.Reverse ();
span.innerhtml = str.replace (/.$/, str.Charat (str.Length-1) == "↓"? "↑": "↓");
}outro{
this.rows.sort (this.comPare (td.getAttribute ('clos'), tipo));
span.innerhtml = span.innerhtml + "↑";
this.sortcol! = null && (this.sortcol.getElementsByTagName ('span') [0] .innerhtml = this.sortcol.getElementsByTagName ('span') [0] .innerhtml.replace (/.
};
for (var i = 0, l = this.rows.length; i <l; i ++)
frag.appendchild (this.rows [i]);
this.table.tbodies [0] .appendChild (frag);
if (sys.ie6) {
para (var s neste.CheckBox)
this.CheckBox [s] .Checked = true;
}
this.sortcol = td; // registra qual coluna está classificando
},
Compare: function (n, tipo) {
Função de retorno (A1, A2) {
var convert = {
int: function (v) {return parseint (v)},
float: function (v) {return parsefloat (v)},
Data: function (v) {return v.toString ()},
String: function (v) {return v.toString ()}
};
! convert [type] && (convert [type] = function (v) {return v.toString ()});
a1 = convert [type] (a1.Cells [n] .innerhtml);
a2 = convert [type] (a2.Cells [n] .innerhtml);
retornar A1 == A2? 0: A1 <A2? -1: 1;
};
},
Editar: function (e) {
var elem = this.inputtd = e.srcelement || E.Target;
if (! elem.getAttribute ('edit')) retornar;
this.input.value = elem.innerhtml;
elem.innerhtml = "";
elem.appendChild (this.input);
this.input.focus ();
},
Salvar: function (elem) {
var editinfo = this.editconfig [elem.parentnode.getAttribute ('edit')], status = {
"[função do objeto]": 'comprimento' em editinfo.rule && editinfo.rule (this.input.value) || false,
"[objeto regexp]": 'teste' em editinfo.rule && editinfo.rule.test (this.input.value) || false
} [Object.prototype.tostring.call (editinfo.rule)], _ self = this;
// Se as condições não atenderem aos requisitos, modifique as informações rápidas
typeof status! = "boolean" && (editinfo.message = status);
if (status === true) {
this.inputtd.innerhtml = this.input.value;
this.inputtd = null;
}outro{
alerta (editinfo.message);
// Use input.focus () diretamente sob o Firefox e não pode ser executado sem executar o setTimeout
setTimeout (function () {_ self.input.focus ()}, 0);
}
},
Theadhover: function (e) {
var elem = e.srcement || E.Target;
if (elem.nodename.tolowercase () === 'td' && this.closconfig.on) {
this.ClosConfig.totd = elem.getAttribute ('clos');
! hasclass (elem, 'tover') && addclass (elem, 'tover');
}
},
theadout: function (e) {
var elem = e.srcement || E.Target;
if (elem.nodename.tolowercase () === 'td' && this.closconfig.on) removeclass (elem, 'Thover')
},
DragorWidth: function (e) {
var elem = e.srcement || E.Target, widthConfig = this.WidthConfig;
// Execute arrastar e soltar
if (elem.nodename.tolowercase () === 'td') {
this.Closconfig.td = elem.getAttribute ('clos');
addListener (documento, 'mousemove', bindaseventListener (this, this.dragmove));
addListener (documento, 'mouseup', bind (this, this.Dragup));
this.ClosConfig.on = true;
Sys.ie?this.head.setCapture (false): e.preventDefault ();
}
// executa o escalonamento de largura
if (elem.nodename.tolowercase () === 'div') {
Sys.ie? (E.cancelbubble = true): etoppropagation ();
// Se for o último TD, o div não será escalado
if (this.headtds [this.headtds.length-1] === elem.parentnode) retorna
Sys.ie?this.head.setCapture (false): e.preventDefault ();
widthconfig.x = e.clientX;
widthconfig.td = elem.parentnode;
widthconfig.NextTd = widthconfig.td.nextsbling;
while (widthconfig.nexttd.nodename.tolowercase ()! = "td") {
widthConfig.NextTd = widthconfig.nexttd.nextsibling;
};
widthconfig.tdwidth = widthconfig.td.offsetWidth;
widthConfig.NextTdWidth = widthconfig.nexttd.offsetWidth;
this.line.style.Height = this.table.offsetheight +"px";
addListener (documento, 'mousemove', bindaseventListener (this, this.WidthMove));
addListener (documento, 'mouseup', bind (this, this.Widthup));
}
},
DragMove: function (e) {
Window.GetSelection? window.getSelection (). removeallLanges (): document.selection.empty ();
setStyle (this.div, {display: "bloco", esquerda: e.clientX+9+"px", topo: e.clienty+20+"px"});
},
arrastar: function () {
var closConfig = this.ClosConfig, linhas = this.table.getElementsByTagName ('tr'), td, n, o, i = 0, l = linhas.lengthn;
this.div.style.display = "nenhum";
Removelistener (Document, 'Mousemove');
Removelistener (Document, 'MouseUp');
Sys.ie && this.thead.releaseCapture ();
ClosConfig.on = false;
if (ClosConfig.totd === NULL) retornar;
removeclass (this.headtds [closconfig.totd], 'thover');
// Nenhuma substituição de coluna é realizada na mesma coluna
if (ClosConfig.td === ClosConfig.totd) retornar;
// Verifique a substituição da coluna
if (ClosConfig.td*1+1 === ClosConfig.totd*1) {
n = ClosConfig.totd;
o = ClosConfig.td;
}outro{
n = ClosConfig.td;
o = ClosConfig.totd;
}
para (; i <l; i ++) {
td = linhas [i] .getElementsByTagName ('td');
linhas [i] .InsertBefore (td [n], td [o]);
}
// Reentifique o cabeçalho
for (i = 0, l = this.headtds.length; i <l; i ++)
this.headtds [i] .SetAttribute ('clos', i);
closConfig.totd = closConfig.td = null;
},
widthmove: function (e) {
Window.GetSelection? window.getSelection (). removeallLanges (): document.selection.empty ();
var widthConfig = this.widthConfig, x = e.clientX - widthconfig.x, esquerda = e.clientX, clientx = esquerda;
if (clientx <widthconfig.x && widthconfig.x - clientx> widthconfig.tdwidth- this.minwidth) {
esquerda = widthconfig.x - widthconfig.tdwidth+this.minwidth;
}
if (clientx> widthconfig.x && clientx - widthconfig.x> widthconfig.nexttdwidth- this.minwidth) {
esquerda = widthconfig.x + widthconfig.nexttdwidth- this.minwidth;
}
setStyle (this.line, {display: "block", esquerda: esquerda+"px"});
},
Widthup: function () {
this.line.style.display = "nenhum";
var widthConfig = this.widthConfig, x = parseint (this.line.style.left) - widthconfig.x;
widthconfig.nexttd.style.width = widthconfig.nextTdWidth -x -1 +'px';
widthconfig.td.style.width = widthconfig.tdwidth + x -1 + 'px';
Sys.ie && this.thead.releaseCapture ();
Removelistener (Document, 'Mousemove');
Removelistener (Document, 'MouseUp');
}
});
window.onload = function () {
função checkName (val) {
if (val.replace (/^/s+$/g, '') === '') retornar o nome do nome da entrada não pode estar vazio ';
if (val.Replace (/^/s+|/s+$/, ''). Comprimento> 10) retornar 'o comprimento do nome não pode ser maior que 10 caracteres';
if (!/^[/u4e00-/u9fa5a-z]+$/i.test (val)) retornar 'o nome só pode ser inserido em chinês ou letras';
retornar true;
};
função checkRemark (val) {
if (val.Replace (/^/s+$/g, '') === '') retorna a entrada da nota não pode estar vazia ';
if (val.Replace (/^/s+|/s+$/, ''). Comprimento> 15) Retorno 'O comprimento das observações não pode ser maior que 15 caracteres';
if (!/^[/u4e00-/u9fa5/w/s]+$/i.test (val)) Retorno 'Notas' só podem entrar no espaço de sublinhamento numérico chinês ';
retornar true;
}
var set = [
{id: 0, tipo: "int"},
{id: 2, tipo: "string", editar: {regra: checkName, mensagem: ''}},
{id: 3, Tipo: "Date", Edit: {regra:/^/d {4}/-/d {2}/-/d {2} $/, mensagem: "Digite a data 1985-02-30 neste formato"}},
{id: 4, tipo: "string", editar: {regra: checkRemark, mensagem: ''}}
];
nova tabela ($ ("guia"), set);
}
</script>
</body>
</html>
Bugs conhecidos:
O texto chinês IE6 não envolve automaticamente
É realmente irritante que letras e números não os envolvam automaticamente no IE.
Clicar no navegador Chrome parece ser um grande problema e fazer testes locais será melhor