有没有办法使用HTML5大纲算法和CSS(可能还有JS)生成文档导航?

时间:2013-04-08 18:14:51

标签: javascript css html5 tableofcontents

有没有办法使用HTML5大纲算法和CSS(以及可能的JS)生成文档导航,就像TeX可以生成目录一样?

编辑:有没有一种方法可以显示HTML文档的链接轮廓而无需显式编写?我在想TeX中的\tableofcontents之类的东西。因此,例如,空的<nav>标记将填充指向页面中各部分的无序链接列表。

1 个答案:

答案 0 :(得分:3)

对于将从文档大纲创建自动toc的javascript,您必须暂时开发自己的。 [我发现实际上没有复制粘贴解决方案]

研究这个:

和这个

[<强> ADDON

来自用户@unor的建议阅读:github.com/DylanFM/outliner已将我发送到此jsFiddle,其中还有另一个javascript启动。

的Javascript

// See http://html5doctor.com/document-outlines/
// That article begins with info on HTML4 document outlines
// This doesn't do that yet, it just handles the HTML5 stuff beneath in the article
// I'm sure there are problems with handling that HTML5 stuff tho

var headingElements = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6'],
sectioningElements = ['SECTION', 'ARTICLE', 'NAV', 'ASIDE'];

function makeOutline(root) {
var ar = [],
    el = root.firstChild,
    nested, hg;
while(el) {
    // If it's a sectioning element, create a new level in the outline
    if(sectioningElements.indexOf(el.tagName) > -1) {
        nested = makeOutline(el);
        if(nested.every(function(i){ return typeof i !== 'string'; })) {
            nested.unshift('Untitled ' + el.tagName.toLowerCase());
        }
        ar.push(nested);
    } else if(headingElements.indexOf(el.tagName) > -1) {
        ar.push(el.textContent);
    } else if(el.tagName === 'HGROUP') {
        hg = undefined;
        // Find the highest heading element within
        // Use its text, otherwhise it's untitled
        try {
            headingElements.forEach(function(t) {
                els = el.getElementsByTagName(t);
                if(els.length) {
                    hg = els[0].textContent;
                    throw BreakException;
                }
            });
        } catch(e) {}
        if(!hg) {
            hg = 'Untitled hgroup';
        }
        ar.push(hg);
    }
    el = el.nextSibling;
}
return ar;
};

var outline = makeOutline(document.body);

// This is just used for displaying the outline. 
// Inspect the outline variable to see the generated array:
// console.log(outline);

function describeOutline(outline) {
var indentForDepth = function(depth) {
    var str = '';
    for(i=depth;i>0;i--) {
        str += '\t';
    }
    return str;
},
childrenAreStrings = function(ar, depth) {
    var depth = (depth && (depth + 1)) || 1;
    return ar.map(function(item) {
        if({}.toString.call(item)=='[object Array]') {
            return childrenAreStrings(item, depth).join('\n');
        } else {
            return indentForDepth(depth) + '- ' + String(item);
        }
    });
};
// Make sure all items in ar are strings
return childrenAreStrings(outline).join('\n');    
}

(document.getElementsByTagName('pre')[0]).textContent = describeOutline(outline);