これを実行したい場合は、私の getElementByTagNames() 関数も必要です。
, and I also want these to be displayed in the ToC. I added these new links to the inside the ToC.
Copy code The code is as follows:
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 the title is h4 or h5 I will add an extra class.
Copy code The code is as follows:
if (toBeTOCced[i].nodeName == 'H4 ')
tmp.className = ' indent';
if (toBeTOCced[i].nodeName == 'H5')
tmp.className = ' extraindent';
Now we need to link the a element to its actual title. This requires a unique ID. However, these headers may already contain an ID. I don't want to break the original internal linking, so I prefer to use the original ID of the title. Only if the title doesn't have an ID do I create a new ID.
Copy code The code is as follows: var headerId = toBeTOCced[i].id || 'link' i ;
The href attribute of the link we just created should be #headerId, and the title itself also has an ID.
Copy code The code is as follows:
tmp.href = '#' headerId;
toBeTOCced[i].id = headerId;
A special case: if the header is H2, which is the top of the page, you will also get an ID.
Copy code The code is as follows:
if (toBeTOCced[i].nodeName == 'H2 ') {
tmp.innerHTML = 'Top';
tmp.href = '#top';
toBeTOCced[i].id = 'top';
}
}
Now that the form is produced, we return it to the place where it was called.
Copy code The code is as follows:return y;}
Display and Hide ToC
The last function is used to show and hide ToC. Very simple, first detect the status of ToC, and then generate a new text and display value based on the information.
Copy code The code is as follows:
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;
}
This function is called when the user clicks so that he can switch the display of ToC. In addition, the ToC will be hidden immediately when the user clicks on the link.
Translation address: http://www.quirksmode.org/dom/toc.html
Please keep the following information for reprinting
Author: Beiyu (tw:@rehawk)