// 共用行為:表格加捲動外框、依 h2 切段、產生目錄。各版型自己決定要用哪幾個。 (function (w) { 'use strict'; // 寬表格包一層可橫捲的外框,整頁就不會被撐開。 function wrapTables(root) { root.querySelectorAll('table').forEach(function (t) { if (t.parentElement && t.parentElement.classList.contains('table-wrap')) return; var box = document.createElement('div'); box.className = 'table-wrap'; t.parentNode.insertBefore(box, t); box.appendChild(t); }); } // 依 h2 把內容切成一段一段。h2 之前的內容自成第一段(前言)。 function splitBySection(root) { var nodes = Array.prototype.slice.call(root.childNodes); var sections = []; var current = null; function open(headingText) { current = document.createElement('section'); current.className = 'jsc-section'; current.dataset.title = headingText || ''; sections.push(current); } nodes.forEach(function (node) { if (node.nodeType === 1 && node.tagName === 'H2') { open(node.textContent.trim()); } else if (!current) { if (node.nodeType === 3 && !node.textContent.trim()) return; open(''); } current.appendChild(node); }); root.innerHTML = ''; sections.forEach(function (s) { root.appendChild(s); }); return sections; } // 依 h2、h3 產生目錄,塞進指定容器。標題沒有 id 就補一個。 function buildToc(root, target) { var heads = root.querySelectorAll('h2, h3'); if (!heads.length) { target.remove(); return; } var list = document.createElement('ul'); heads.forEach(function (h, i) { if (!h.id) h.id = 'sec-' + (i + 1); var li = document.createElement('li'); li.className = 'toc-' + h.tagName.toLowerCase(); var a = document.createElement('a'); a.href = '#' + h.id; a.textContent = h.textContent.trim(); li.appendChild(a); list.appendChild(li); }); target.appendChild(list); } w.jsc = { wrapTables: wrapTables, splitBySection: splitBySection, buildToc: buildToc }; })(window);