DIV CSS 佈局教程網

用原生 JS 自動產生文章標題樹(TOC)
編輯:關於JavaScript     

長文閱讀時,側邊的標題導覽幾乎是必需品。它的原理其實非常單純:迴圈掃過文章容器,把 h2 與 h3 抓出來,為每個標題配一個錨點 id,再生成對應的 li 塞進選單。全程不需要任何函式庫。

HTML 結構

左側是文章 #article,右側是空的 #articleMenu 清單,另外兩個 span 作為收合與展開的切換鈕。

 <div class="contextBox"> <div id="article"> <h2>二級標題</h2> <h3>三級標題</h3> <p>hello hello hello hello hello hello hello hello hello hello hello hello</p> <h3>三級標題</h3> <h3>三級標題</h3> <h3>三級標題</h3> <h3>三級標題</h3> <p>hello hello hello hello hello hello hello hello hello hello hello</p> <h2>二級標題</h2> <h3>三級標題</h3> <h3>三級標題</h3> <p>world world world world world world world world world world world world world world world world world world world world world world world world world world world world world world world </p> <h3>三級標題</h3> <h3>三級標題</h3> <h2>二級標題</h2> <h3>三級標題</h3> <h3>三級標題</h3> <h2>二級標題</h2> <h3>三級標題</h3> <h3>三級標題</h3> <h2>二級標題</h2> <h3>三級標題</h3> <h3>三級標題</h3> </div> <div class="articleMenu-box" id="articleMenu_box"> <span class="articleMenu-open" id="articleMenu_open"></span> <ul class="articleMenu hello" id="articleMenu"> <span class="articleMenu-close" id="articleMenu_close"></span> </ul> </div> </div>

CSS

 * { margin: 0; padding: 0; border: 0; } body { font: 16px/1.5; } ul li, ol li { list-style: none; } .contextBox { position: relative; width: 960px; margin: 0 auto; } #article { margin-left: 200px; border: 1px #eee solid; padding: 15px; } .articleMenu a { text-decoration: none; color: #333; } .articleMenu a:hover { color: #f85455; } .articleMenu-box { width: 170px; position: absolute; left: 10px; top: 10px; } .articleMenu { padding: 10px; border: 1px solid #ccc; box-shadow: 2px 2px 2px #eee; } .titleH2, .titleH3 { line-height: 1.5em; } .titleH2 { font-weight: bold; } .titleH3 { margin-left: 20px; } .articleMenu .articleMenu-close, .articleMenu-open { display: inline-block; position: absolute; right: 0; top: 0; height: 44px; width: 44px; cursor: pointer; } .articleMenu-open { background: url("https://www.dengzhr.com/wp-content/themes/dengzhr/images/icon_articleMenu_open.png") no-repeat 50% 50%; display: none; } .articleMenu .articleMenu-close { background: url("https://www.dengzhr.com/wp-content/themes/dengzhr/images/icon_articleMenu_close.png") no-repeat 50% 50%; }

JavaScript 主體

titleHgroup 是核心函式,接收四個參數:文章父元素、承載選單的 ul、以及 h2 與 h3 各自要套用的 class 名稱。它先取 children(只含元素節點,避開空白文字節點的干擾),建立一個 DocumentFragment 暫存結果,迴圈中依標籤名分派到內部的 titleToList,為標題配上 h2 + i 形式的 id、包成 <a href="#..."> 走錨點定位,最後一次 appendChild 把整批節點掛進 DOM——只觸發一次重排。

 var article = document.getElementById("article"); var articleHgroupMenu = document.getElementById("articleMenu"); // 關閉和展開文檔樹 var articleMenu_open = document.getElementById("articleMenu_open"); var articleMenu_close = document.getElementById("articleMenu_close"); articleMenu_close.onclick = function() { articleHgroupMenu.style.display = "none"; articleMenu_open.style.display = "block"; }; articleMenu_open.onclick = function() { articleHgroupMenu.style.display = "block"; articleMenu_open.style.display = "none"; }; // titleHgroup(article, articleHgroupMenu, "titleH2", "titleH3"); // 獲得obj下的直接子元素中為標題h2~h3的標題元素 // 參數說明:hgroupParent為包含h2和h3的直接父元素;MenuList為承載新建文章列表的ul元素; // h2ClassName、h3ClassName分別為新建文章列表中對應h2、h3的li自列表的Class屬性; function titleHgroup(hgroupParent, MenuList, h2ClassName, h3ClassName) { var hgroup = hgroupParent.children; // 創建文檔片段,來包裹自動生成的h2、h3對應生成的li列表 var fragment = document.createDocumentFragment(); for(i = 0; i < hgroup.length && hgroup[i].nodeType === 1; i++) { // 為對應類型的標題生成li列表 // 參數說明:hType為標題的類型如h1~h6;className為標題對應的li列表的class屬性值; function titleToList(hType, className) { var li = document.createElement("li"); li.className = className; // 為li標簽內部添加a標簽,用錨點進行定位; hgroup[i].id= hType + i; li.innerHTML = ("<a href='#" + hType + i + "'>" + hgroup[i].innerHTML +"</a>"); fragment.appendChild(li); } // 當遍歷中標題元素為h2時,調用titleToList(hType, className)新增對應的li列表; if(hgroup[i].nodeName.toLowerCase() == "h2") { titleToList("h2", h2ClassName); } // 當遍歷中標題元素為h3時,調用titleToList(hType, className)新增對應的li列表; if(hgroup[i].nodeName.toLowerCase() == "h3") { titleToList("h3", h3ClassName); } } // 將承載好對應li元素集合的文檔片段fragment添加到DOM(即在DOM中包裹li列表的父元素)中去; MenuList.appendChild(fragment); }

完整可執行範例

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>原生JS實現自動生成文章標題樹</title> <style type="text/css"> * { margin: 0; padding: 0; border: 0; } body { font: 16px/1.5; } ul li, ol li { list-style: none; } .contextBox { position: relative; width: 960px; margin: 0 auto; } #article { margin-left: 200px; border: 1px #eee solid; padding: 15px; } .articleMenu a { text-decoration: none; color: #333; } .articleMenu a:hover { color: #f85455; } .articleMenu-box { width: 170px; position: absolute; left: 10px; top: 10px; } .articleMenu { padding: 10px; border: 1px solid #ccc; box-shadow: 2px 2px 2px #eee; } .titleH2, .titleH3 { line-height: 1.5em; } .titleH2 { font-weight: bold; } .titleH3 { margin-left: 20px; } .articleMenu .articleMenu-close, .articleMenu-open { display: inline-block; position: absolute; right: 0; top: 0; height: 44px; width: 44px; cursor: pointer; } .articleMenu-open { background: url("https://www.dengzhr.com/wp-content/themes/dengzhr/images/icon_articleMenu_open.png") no-repeat 50% 50%; display: none; } .articleMenu .articleMenu-close { background: url("https://www.dengzhr.com/wp-content/themes/dengzhr/images/icon_articleMenu_close.png") no-repeat 50% 50%; } </style> </head> <body> <div class="contextBox"> <div id="article"> <h2>二級標題</h2> <h3>三級標題</h3> <p>hello<br /> hello<br /> hello<br /> hello<br /> hello<br /> hello<br /><br /> hello<br /> hell<br />o hel<br />lo hell<br />o he<br />llo hello</p> <h3>三級標題</h3> <h3>三級標題</h3> <h3>三級標題</h3> <h3>三級標題</h3> <p>hello hello hello hello hello hello hello hello hello hello hello</p> <h2>二級標題</h2> <h3>三級標題</h3> <h3>三級標題</h3> <p>world w<br />orld <br />world world wo<br />rld world wo<br />rld world world wor<br />ld world world <br />world <br />worl<br />d world<br /> w<br />orld <br />world wo<br />rld wor<br />ld world wor<br />ld world worl<br />d w<br />or<br />ld<br /> <br />world <br />world <br />world<br /> <br />wo<br />rld wo<br />rld w<br />orld w<br />orld </p> <h3>三級標題</h3> <h3>三級標題</h3> <h2>二級標題</h2> <h3>三級標題</h3> <h3>三級標題</h3> <h2>二級標題</h2> <h3>三級標題</h3> <h3>三級標題</h3> <h2>二級標題</h2> <h3>三級標題</h3> <h3>三級標題</h3> </div> <div class="articleMenu-box" id="articleMenu_box"> <span class="articleMenu-open" id="articleMenu_open"></span> <ul class="articleMenu hello" id="articleMenu"> <span class="articleMenu-close" id="articleMenu_close"></span> </ul> </div> </div> <script type="text/javascript"> var article = document.getElementById("article"); var articleHgroupMenu = document.getElementById("articleMenu"); // 關閉和展開文檔樹 var articleMenu_open = document.getElementById("articleMenu_open"); var articleMenu_close = document.getElementById("articleMenu_close"); articleMenu_close.onclick = function() { articleHgroupMenu.style.display = "none"; articleMenu_open.style.display = "block"; }; articleMenu_open.onclick = function() { articleHgroupMenu.style.display = "block"; articleMenu_open.style.display = "none"; }; // titleHgroup(article, articleHgroupMenu, "titleH2", "titleH3"); // 獲得obj下的直接子元素中為標題h2~h3的標題元素 // 參數說明:hgroupParent為包含h2和h3的直接父元素;MenuList為承載新建文章列表的ul元素; // h2ClassName、h3ClassName分別為新建文章列表中對應h2、h3的li自列表的Class屬性; function titleHgroup(hgroupParent, MenuList, h2ClassName, h3ClassName) { var hgroup = hgroupParent.children; // 創建文檔片段,來包裹自動生成的h2、h3對應生成的li列表 var fragment = document.createDocumentFragment(); for(i = 0; i < hgroup.length && hgroup[i].nodeType === 1; i++) { // 為對應類型的標題生成li列表 // 參數說明:hType為標題的類型如h1~h6;className為標題對應的li列表的class屬性值; function titleToList(hType, className) { var li = document.createElement("li"); li.className = className; // 為li標簽內部添加a標簽,用錨點進行定位; hgroup[i].id= hType + i; li.innerHTML = ("<a href='#" + hType + i + "'>" + hgroup[i].innerHTML +"</a>"); fragment.appendChild(li); } // 當遍歷中標題元素為h2時,調用titleToList(hType, className)新增對應的li列表; if(hgroup[i].nodeName.toLowerCase() == "h2") { titleToList("h2", h2ClassName); } // 當遍歷中標題元素為h3時,調用titleToList(hType, className)新增對應的li列表; if(hgroup[i].nodeName.toLowerCase() == "h3") { titleToList("h3", h3ClassName); } } // 將承載好對應li元素集合的文檔片段fragment添加到DOM(即在DOM中包裹li列表的父元素)中去; MenuList.appendChild(fragment); } </script> </body> </html>

要更進一步的話

三個實務上的改進方向。用 querySelectorAll('h2, h3') 取代 children 迴圈,能支援任意嵌套層級,不必限定標題必須是「直接子元素」;配合 IntersectionObserver 就能做到捲動時自動高亮當前章節。標題文字請用 textContent 而非 innerHTML,既避免標題內含 HTML 時的注入風險,也不會把行內標籤一起帶進選單。收合按鈕改用 hidden 屬性或 class 切換,並為容器加上 aria-label="目錄"、為收合鈕加上 aria-expanded,鍵盤與螢幕閱讀器使用者才能正確操作。

以上就是自動產生文章標題樹的完整做法,骨架很輕,加上高亮與響應式之後就是可以直接用在部落格或文件站的成品了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved