简单的HTML漂亮打印

时间:2011-12-01 21:28:40

标签: javascript jquery html pretty-print pre

  

http://jsfiddle.net/JamesKyle/L4b8b/

这可能是徒劳的,但我个人认为这是可能的。

我不是Javascript或jQuery的最佳人选,但我认为我已经找到了一种简单的方法来为html制作简单的漂亮图纸。

这个漂亮的印刷中有四种类型的代码:

  1. 纯文本
  2. 元素
  3. 属性
  4. 为了对其进行样式化,我希望将elementsattibutesvalues用自己的类包围。


    我这样做的第一种方法是存储每一种元素和属性(如下所示),然后用相应的跨度包装它们

    $(document).ready(function() {
    
        $('pre.prettyprint.html').each(function() {
    
            $(this).css('white-space','pre-line');
    
            var code = $(this).html();
    
            var html-element = $(code).find('a, abbr, acronym, address, area, article, aside, audio, b, base, bdo, bdi, big, blockquote, body, br, button, canvas, caption, cite, code, col, colgroup, command, datalist, dd, del, details, dfn, div, dl, dt, em, embed, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html, i, img, input, ins, kbd, keygen, label, legend, li, link, map, mark, meta, meter, nav, noscript, object, ol, optgroup, option, output, p, param, pre, progress, q, rp, rt, ruby, samp, script, section, select, small, source, span, strong, summary, style, sub, sup, table, tbody, td, textarea, tfoot, th, thead, title, time, tr, track, tt, ul, var, video, wbr');
    
            var html-attribute = $(code).find('abbr, accept-charset, accept, accesskey, actionm, align, alink, alt, archive, axis, background, bgcolor, border, cellpadding, cellspacing, char, charoff, charset, checked, cite, class, classid, clear, code, codebase, codetype, color, cols, colspan, compact, content, coords, data, datetime, declare, defer, dir, disabled, enctype, face, for, frame, frameborder, headers, height, href, hreflang, hspace, http-equiv, id, ismap, label, lang, language, link, longdesc, marginheight, marginwidth, maxlength, media, method, multiple, name, nohref, noresize, noshade, nowrap, object, onblur, onchange,onclick ondblclick onfocus onkeydown, onkeypress, onkeyup, onload, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onreset, onselect, onsubmit, onunload, profile, prompt, readonly, rel, rev, rows, rowspan, rules, scheme, scope, scrolling, selected, shape, size, span, src, standby, start, style, summary, tabindex, target, text, title, type, usemap, valign, value, valuetype, version, vlink, vspace, width');
    
            var html-value = $(code).find(/* Any instance of text inbetween two parenthesis */);
    
            $(element).wrap('<span class="element" />');
            $(attribute).wrap('<span class="attribute" />');
            $(value).wrap('<span class="value" />');
    
            $(code).find('<').replaceWith('&lt');
            $(code).find('>').replaceWith('&gt');
        });
    });
    

    我想到的第二种方法是将elements检测为任意数量的文本被两个&lt; &gt;然后检测attributes作为element内部的文本,该文本被两个空格包围或者紧跟在后面有=

    $(document).ready(function() {
    
        $('pre.prettyprint.html').each(function() {
    
            $(this).css('white-space','pre-line');
    
            var code = $(this).html();
    
            var html-element = $(code).find(/* Any instance of text inbeween two < > */);
    
            var html-attribute = $(code).find(/* Any instance of text inside an element that has a = immeadiatly afterwards or has spaces on either side */);
    
            var html-value = $(code).find(/* Any instance of text inbetween two parenthesis */);
    
            $(element).wrap('<span class="element" />');
            $(attribute).wrap('<span class="attribute" />');
            $(value).wrap('<span class="value" />');
    
            $(code).find('<').replaceWith('&lt');
            $(code).find('>').replaceWith('&gt');
        });
    });
    

    如果可能的话,如何对其中任何一个进行编码

      

    再次,你可以在这里看到这个jsfiddle:   http://jsfiddle.net/JamesKyle/L4b8b/

3 个答案:

答案 0 :(得分:18)

不要太确定你已经得到了所有的东西,以便在如此少的行中打印漂亮的HTML。我花了一年多的时间和2000行来确定这个话题。您可以直接使用我的代码或重构它以满足您的需求:

https://github.com/prettydiff/prettydiff/blob/master/lib/markuppretty.js(和Github project

您可以在http://prettydiff.com/?m=beautify&html

进行演示

它需要这么多代码的原因是人们似乎并不理解或重视文本节点的重要性。如果您在美化过程中添加新的和空的文本节点,那么您做错了,可能会破坏您的内容。此外,通过其他方式将其搞砸并从内容中移除空白区域也非常容易。您必须小心这些,否则您将完全破坏文档的完整性。

此外,如果您的文档包含CSS或JavaScript,该怎么办?这些也应该是非常印刷的,但是与HTML有着非常不同的要求。甚至HTML和XML也有不同的要求。请相信我认为这不是一件简单的事情。 HTML Tidy已经存在了十多年,并且仍然搞砸了许多边缘案例。

据我所知,我的markup_beauty.js应用程序是为HTML / XML编写的最完整的漂亮打印机。我知道这是一个非常大胆的声明,也许是傲慢的,但到目前为止它从未受到过挑战。看看我的代码,如果你需要的东西没有做,请告诉我,我会把它添加进来。

答案 1 :(得分:2)

我个人会用pre包装HTML,而不是尝试做任何漂亮的打印。有很多库用于进行代码格式化只是google pretty print。只需用pre包装HTML就会自动使其成为“打印”代码。

对于JavaScript,您可以使用JSON.stringify通过为嵌套结构传入大量空格来重新创建代码。

JSON.stringify({ name: 'value' }, null, 2); //Change to four, for four spaces

答案 2 :(得分:-1)

如果你正在做这个客户端,并且你已经拥有了DOM,那么在你自己插入适当的标签时序列化它会更有效,而不是一次序列化整个子树然后尝试重新分析它

相关问题