콩바구니의 그림일기

자바스크립트 자동 목차 생성


By 콩바구니 ~ 2월 8th, 2009. Filed under: XHTML, 창작.

관하여..

자바스크립트로, 본문중에 제목태그 <h1> ~ <h6> 와 제목태그에 인접한 P 태그의 정보를 읽어와서 목차를 생성합니다.
익스플로러 7, 익스플로러 8, 사파리, 파이어폭스, 오페라, 구글크롬 에서 정상 작동합니다. 익스플로러 6은 테스트해보지 않았습니다.

주의사항

이 스크립트를 사용하면, 글을 작성할때 제목태그를 올바로 사용하셔야 합니다. 잘못 사용되면 목차가 제대로 생성되지 않을수도 있습니다.

올바른 제목 사용 예

  1. <h2>강아지의 종류</h2>
    1. <h3>큰강아지</h3>
    2. <p>큰강아지는 덩치가 매우 큰 강아지가 이에 속한다</p>
    3. <h3>작은강아지</h3>
    4. <p>작은 강아지는 덩치가 작은 강아지를 말한다. </p>
  2. <h2>고양이의 종류</h2>
    1. <h3>얼룩고양이</h3>
    2. <p>얼룩무늬가 있는 고양이다. 3색 얼룩이 있는 고양이도 있는데, 수컷의 3색고양이는 매우 드믈다고 한다.</p>
    3. <h3>턱시도고양이</h3>
    4. <p>검튼털과 휜털의 무뉘가 마치 턱시도를 입은듯한 고양이를 일컫는다. 왠지 행동거지가 신사적일것 같다.</p>

바르지 못한 제목 사용 예

  1. <h6>한국의 위인들</h6>
    1. <h5>홍길동</h5>
    2. <p>아버지를 아버지라 부르지 못하고 형을 형이라 부르지 못하니…</p>
    3. <h2>김삿갓</h2>
    4. <p>김삿갓 김삿갓 나는 좋아 김삿갓</p>
    5. <h3>김선달</h3>
    6. <p>대동강물 팔아먹은 유쾌한 사기꾼</p>
    7. <h4>2MB</h4>
    8. <p>일본 오사카카에서 건너온 설치류에 속하는 동물. 현재 파란지붕 아래 서식중. 두뇌용량이 2MB라는 소문이 있다. </p>

Javasctipt

사용된 자바스크립트 코드는 다음과 같습니다.
조금 복잡합니다.

  1. // JavaScript Document
  2. function addLoadEvent(func) {
    1. var oldonLoad = window.onload;
    2. if (typeof window.onload != ‘function’) {
      1. window.onload = func;
      2. }
    3. else {
      1. window.onload = function(){
        1. oldonLoad();
        2. func();
        3. }
      2. }
    4. }
  3. function animationHeight(item_el,nowHeight,toHeight,speed){
    1. if (!item_el.height) item_el.height = nowHeight;
    2. item_el.height = item_el.height + Math.ceil((toHeight-nowHeight)/10);
    3. item_el.style.height = item_el.height + “px”;
    4. if (item_el.height > 0) {item_el.style.display = “block”;} else {item_el.style.display = “none”;}
    5. if (nowHeight < toHeight && item_el.height < toHeight){
      1. item_el.timeout = setTimeout(function anime() { animationHeight(item_el,nowHeight,toHeight,speed);},speed);
      2. }
    6. else if ( nowHeight > toHeight && item_el.height > toHeight) {
      1. item_el.timeout = setTimeout(function anime() { animationHeight(item_el,nowHeight,toHeight,speed);},speed);
      2. }
    7. }
  4. addLoadEvent(autoIndex2);
    1. function autoIndex2(){
      1. if (!document.getElementById) return false;
      2. if (!document.getElementsByTagName) return false;
      3. var content_el = document.getElementById(“content”);
      4. var all_el = document.getElementsByTagName(“*”);
      5. var index_el = document.createElement(“div”);
      6. index_el.className = “off”;
      7. var a_el = document.createElement(“a”);
      8. a_el.href=”#”;
      9. a_el.className = “button”
      10. a_el.onclick = function () {
        1. var aniOl= this.parentNode.childNodes[1];
        2. if (aniOl.timeout)clearTimeout(aniOl.timeout);
        3. if (index_el.className == “off”) {
          1. var text = document.createTextNode(“index off”);
          2. animationHeight(aniOl,0,300,30);
          3. this.removeChild(this.childNodes[0]);
          4. this.appendChild(text);
          5. index_el.className = “on”;
          6. return false;
          7. }
        4. else {
          1. animationHeight(aniOl,300,0,30);
          2. var text = document.createTextNode(“index on”);
          3. this.removeChild(this.childNodes[0]);
          4. this.appendChild(text);
          5. index_el.className = “off”;
          6. return false;
          7. }
        5. return false;
        6. }
      11. var text = document.createTextNode(“index on”);
      12. a_el.appendChild(text);
      13. index_el.appendChild(a_el);
      14. index_el.id=”kongbaguni_AutoIndex”;
      15. var ol_el = document.createElement(“ol”);
      16. index_el.appendChild(ol_el);
      17. var titleCount = 0;
      18. var test = “”;
      19. var title_el = new Array();
      20. var li_el = new Array();
      21. var tagList = “H1;H2;H3;H4;H5;H6;”;
      22. for (i=0;i<all_el.length;i++){
        1. var a_el = document.createElement(“a”);
        2. li_el[titleCount] = document.createElement(“li”);
        3. if (tagList.indexOf(all_el[i].nodeName + “;”)>=0) {
          1. var str = all_el[i].nodeName;
          2. all_el[i].titleRank = parseInt(str.substring(1,2));
          3. title_el[titleCount] = all_el[i];
          4. var text = “”;
          5. for (c=0;c<all_el[i].childNodes.length;c++){
            1. if (all_el[i].childNodes[c].nodeValue) {
              1. text = text + all_el[i].childNodes[c].nodeValue;
              2. }
            2. else {
              1. for (d=0;d<all_el[i].childNodes[c].childNodes.length;d++) {
                1. text = text + all_el[i].childNodes[c].childNodes[d].nodeValue;
                2. }
              2. }
            3. }
          6. if (!all_el[i].id)all_el[i].id = “link”+titleCount + “-”+text;
          7. var text = document.createTextNode(text);
          8. a_el.href =”#”+all_el[i].id;
          9. a_el.appendChild(text);
          10. li_el[titleCount].appendChild(a_el);
          11. ol_el.appendChild(li_el[titleCount]);
          12. if (title_el[titleCount-1]) {
            1. var rank = 1;
            2. var subOl_el = document.createElement(“ol”);
            3. for (var j=1; j<=titleCount; j++){
            4. var oldRank = title_el[titleCount-1].titleRank;
            5. var newRank = title_el[titleCount].titleRank
            6. if (oldRank < newRank) {
              1. li_el[titleCount-1].appendChild(subOl_el);
              2. subOl_el.appendChild(li_el[titleCount]);
              3. }
            7. else if(oldRank == newRank) {
              1. li_el[titleCount-1].parentNode.appendChild(li_el[titleCount]);
              2. }
            8. else {
              1. li_el[titleCount-1].parentNode.parentNode.parentNode.appendChild(li_el[titleCount]);
              2. }
            9. }
          13. }
          14. titleCount ++;
        4. }
        5. if (all_el[i].nodeName == “P” && tagList.indexOf(all_el[i-1].nodeName + “;”)>=0 ) {
          1. var txt = “”;
          2. for (pp=0;pp<all_el[i].childNodes.length;pp++){
            1. if (all_el[i].childNodes[pp].nodeName==”#text”){
              1. txt = txt + all_el[i].childNodes[pp].nodeValue;}
            2. else {
              1. for (ppp = 0; ppp < all_el[i].childNodes[pp].childNodes.length; ppp++){
                1. txt = txt + all_el[i].childNodes[pp].childNodes[ppp].nodeValue;
                2. }
              2. }
            3. }
          3. var str = txt.substring(0,30)+”…”;
          4. var text = document.createTextNode(str);
          5. var liEl = document.createElement(“li”);
          6. var ulEl = document.createElement(“ul”);
          7. liEl.appendChild(text);
          8. ulEl.appendChild(liEl);
          9. li_el[titleCount-1].appendChild(ulEl);
          10. }
        6. }
      23. content_el.insertBefore(index_el,content_el.childNodes[0]);
      24. }

Download

javasctipt-autoindex

One Response to “자바스크립트 자동 목차 생성”

  1. kongbaguni's me2DAY 님의 말:

    콩바구니의 알림…

    자동으로 목차를 생성하는 자바스크립트 를 만들어 보았다.이번것은, ol 과 ul 을 이용하여 유의미한 목차를 생성한다는것과, 생성된 목차를 열고 닫을때 움직이는 효과가 있다는것이 특징이…

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

노무현 전 대통령 서거 삼가 고인의 명복을 빕니다.