자바스크립트 자동 목차 생성
By 콩바구니 ~ 2월 8th, 2009. Filed under: XHTML, 창작.
관하여..
자바스크립트로, 본문중에 제목태그 <h1> ~ <h6> 와 제목태그에 인접한 P 태그의 정보를 읽어와서 목차를 생성합니다.
익스플로러 7, 익스플로러 8, 사파리, 파이어폭스, 오페라, 구글크롬 에서 정상 작동합니다. 익스플로러 6은 테스트해보지 않았습니다.
주의사항
이 스크립트를 사용하면, 글을 작성할때 제목태그를 올바로 사용하셔야 합니다. 잘못 사용되면 목차가 제대로 생성되지 않을수도 있습니다.
올바른 제목 사용 예
- <h2>강아지의 종류</h2>
- <h3>큰강아지</h3>
- <p>큰강아지는 덩치가 매우 큰 강아지가 이에 속한다</p>
- <h3>작은강아지</h3>
- <p>작은 강아지는 덩치가 작은 강아지를 말한다. </p>
- <h2>고양이의 종류</h2>
- <h3>얼룩고양이</h3>
- <p>얼룩무늬가 있는 고양이다. 3색 얼룩이 있는 고양이도 있는데, 수컷의 3색고양이는 매우 드믈다고 한다.</p>
- <h3>턱시도고양이</h3>
- <p>검튼털과 휜털의 무뉘가 마치 턱시도를 입은듯한 고양이를 일컫는다. 왠지 행동거지가 신사적일것 같다.</p>
바르지 못한 제목 사용 예
- <h6>한국의 위인들</h6>
- <h5>홍길동</h5>
- <p>아버지를 아버지라 부르지 못하고 형을 형이라 부르지 못하니…</p>
- <h2>김삿갓</h2>
- <p>김삿갓 김삿갓 나는 좋아 김삿갓</p>
- <h3>김선달</h3>
- <p>대동강물 팔아먹은 유쾌한 사기꾼</p>
- <h4>2MB</h4>
- <p>일본 오사카카에서 건너온 설치류에 속하는 동물. 현재 파란지붕 아래 서식중. 두뇌용량이 2MB라는 소문이 있다. </p>
Javasctipt
사용된 자바스크립트 코드는 다음과 같습니다.
조금 복잡합니다.
- // JavaScript Document
- function addLoadEvent(func) {
- var oldonLoad = window.onload;
- if (typeof window.onload != ‘function’) {
- window.onload = func;
- }
- else {
- window.onload = function(){
- oldonLoad();
- func();
- }
- }
- window.onload = function(){
- }
- function animationHeight(item_el,nowHeight,toHeight,speed){
- if (!item_el.height) item_el.height = nowHeight;
- item_el.height = item_el.height + Math.ceil((toHeight-nowHeight)/10);
- item_el.style.height = item_el.height + “px”;
- if (item_el.height > 0) {item_el.style.display = “block”;} else {item_el.style.display = “none”;}
- if (nowHeight < toHeight && item_el.height < toHeight){
- item_el.timeout = setTimeout(function anime() { animationHeight(item_el,nowHeight,toHeight,speed);},speed);
- }
- else if ( nowHeight > toHeight && item_el.height > toHeight) {
- item_el.timeout = setTimeout(function anime() { animationHeight(item_el,nowHeight,toHeight,speed);},speed);
- }
- }
- addLoadEvent(autoIndex2);
- function autoIndex2(){
- if (!document.getElementById) return false;
- if (!document.getElementsByTagName) return false;
- var content_el = document.getElementById(“content”);
- var all_el = document.getElementsByTagName(“*”);
- var index_el = document.createElement(“div”);
- index_el.className = “off”;
- var a_el = document.createElement(“a”);
- a_el.href=”#”;
- a_el.className = “button”
- a_el.onclick = function () {
- var aniOl= this.parentNode.childNodes[1];
- if (aniOl.timeout)clearTimeout(aniOl.timeout);
- if (index_el.className == “off”) {
- var text = document.createTextNode(“index off”);
- animationHeight(aniOl,0,300,30);
- this.removeChild(this.childNodes[0]);
- this.appendChild(text);
- index_el.className = “on”;
- return false;
- }
- else {
- animationHeight(aniOl,300,0,30);
- var text = document.createTextNode(“index on”);
- this.removeChild(this.childNodes[0]);
- this.appendChild(text);
- index_el.className = “off”;
- return false;
- }
- return false;
- }
- var text = document.createTextNode(“index on”);
- a_el.appendChild(text);
- index_el.appendChild(a_el);
- index_el.id=”kongbaguni_AutoIndex”;
- var ol_el = document.createElement(“ol”);
- index_el.appendChild(ol_el);
- var titleCount = 0;
- var test = “”;
- var title_el = new Array();
- var li_el = new Array();
- var tagList = “H1;H2;H3;H4;H5;H6;”;
- for (i=0;i<all_el.length;i++){
- var a_el = document.createElement(“a”);
- li_el[titleCount] = document.createElement(“li”);
- if (tagList.indexOf(all_el[i].nodeName + “;”)>=0) {
- var str = all_el[i].nodeName;
- all_el[i].titleRank = parseInt(str.substring(1,2));
- title_el[titleCount] = all_el[i];
- var text = “”;
- for (c=0;c<all_el[i].childNodes.length;c++){
- if (all_el[i].childNodes[c].nodeValue) {
- text = text + all_el[i].childNodes[c].nodeValue;
- }
- else {
- for (d=0;d<all_el[i].childNodes[c].childNodes.length;d++) {
- text = text + all_el[i].childNodes[c].childNodes[d].nodeValue;
- }
- }
- for (d=0;d<all_el[i].childNodes[c].childNodes.length;d++) {
- }
- if (all_el[i].childNodes[c].nodeValue) {
- if (!all_el[i].id)all_el[i].id = “link”+titleCount + “-”+text;
- var text = document.createTextNode(text);
- a_el.href =”#”+all_el[i].id;
- a_el.appendChild(text);
- li_el[titleCount].appendChild(a_el);
- ol_el.appendChild(li_el[titleCount]);
- if (title_el[titleCount-1]) {
- var rank = 1;
- var subOl_el = document.createElement(“ol”);
- for (var j=1; j<=titleCount; j++){
- var oldRank = title_el[titleCount-1].titleRank;
- var newRank = title_el[titleCount].titleRank
- if (oldRank < newRank) {
- li_el[titleCount-1].appendChild(subOl_el);
- subOl_el.appendChild(li_el[titleCount]);
- }
- else if(oldRank == newRank) {
- li_el[titleCount-1].parentNode.appendChild(li_el[titleCount]);
- }
- else {
- li_el[titleCount-1].parentNode.parentNode.parentNode.appendChild(li_el[titleCount]);
- }
- }
- }
- titleCount ++;
- }
- if (all_el[i].nodeName == “P” && tagList.indexOf(all_el[i-1].nodeName + “;”)>=0 ) {
- var txt = “”;
- for (pp=0;pp<all_el[i].childNodes.length;pp++){
- if (all_el[i].childNodes[pp].nodeName==”#text”){
- txt = txt + all_el[i].childNodes[pp].nodeValue;}
- else {
- for (ppp = 0; ppp < all_el[i].childNodes[pp].childNodes.length; ppp++){
- txt = txt + all_el[i].childNodes[pp].childNodes[ppp].nodeValue;
- }
- }
- for (ppp = 0; ppp < all_el[i].childNodes[pp].childNodes.length; ppp++){
- }
- if (all_el[i].childNodes[pp].nodeName==”#text”){
- var str = txt.substring(0,30)+”…”;
- var text = document.createTextNode(str);
- var liEl = document.createElement(“li”);
- var ulEl = document.createElement(“ul”);
- liEl.appendChild(text);
- ulEl.appendChild(liEl);
- li_el[titleCount-1].appendChild(ulEl);
- }
- }
- content_el.insertBefore(index_el,content_el.childNodes[0]);
- }
- function autoIndex2(){
콩바구니의 알림…
자동으로 목차를 생성하는 자바스크립트 를 만들어 보았다.이번것은, ol 과 ul 을 이용하여 유의미한 목차를 생성한다는것과, 생성된 목차를 열고 닫을때 움직이는 효과가 있다는것이 특징이…