En Quirksmode, uno de las webs que más respeto, he encontrado este fantástico script que mediante el uso de getElementsByTagNames() monta una tabla de contenidos en tu web de forma completamente automática.
Para ello se encarga de recorrer todos los elementos <h3></h3> y <h4></h4> de la página ofreciendo un enlace rápido (un ancla) hacia ellos. De esta forma podrás generarte dinámicamente mediante Javascript una tabla de contenidos y úbicarla en cualquier parte de tu web a modo de resumen del contenido de la página actual.
El script
function createTOC() {
var y = document.createElement('div');
y.id = 'innertoc';
var a = y.appendChild(document.createElement('span'));
a.onclick = showhideTOC;
a.id = 'contentheader';
a.innerHTML = 'show page contents';
var z = y.appendChild(document.createElement('div'));
z.onclick = showhideTOC;
var toBeTOCced = getElementsByTagNames('h2,h3,h4,h5');
if (toBeTOCced.length < 2) return false;
for (var i=0;i<toBeTOCced.length;i++) {
var tmp = document.createElement('a');
tmp.innerHTML = toBeTOCced[i].innerHTML;
tmp.className = 'page';
z.appendChild(tmp);
if (toBeTOCced[i].nodeName == 'H4')
tmp.className += ' indent';
if (toBeTOCced[i].nodeName == 'H5')
tmp.className += ' extraindent';
var headerId = toBeTOCced[i].id || 'link' + i;
tmp.href = '#' + headerId;
toBeTOCced[i].id = headerId;
if (toBeTOCced[i].nodeName == 'H2') {
tmp.innerHTML = 'Top';
tmp.href = '#top';
toBeTOCced[i].id = 'top';
}
}
return y;
}
var TOCstate = 'none';
function showhideTOC() {
TOCstate = (TOCstate == 'none') ? 'block' : 'none';
var newText = (TOCstate == 'none') ? 'show page contents' : 'hide page contents';
document.getElementById('contentheader').innerHTML = newText;
document.getElementById('innertoc').lastChild.style.display = TOCstate;
}
Únicamente nos queda llamarla en el onload de nuestra página y ella misma nos generará el div con el contenido de nuestra tabla de contenidos.
1 comentarios, 0 referencias
+
#