如果你也想这么做,那么你还需要我的getElementByTagNames()函数。
代码如下:
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;
}
解释
这段代码运行如下:
准备阶段
首先我创建一个<div id="innertoc">来放置表格内容
代码如下:
function createTOC() {
var y = document.createElement('div');
y.id = 'innertoc';
然后在他的上面添加一个<span>标签。点击这个元素就会运行showhideTOC()函数,我会在下面解释。
新闻热点
疑难解答
图片精选