Format code with line number.
This task use javascript to format code in <pre> tag with line number.
Format code with line number using jQuery
- Put code in <pre class='code'></pre> tags.
- Add following code at the end of page.
<style> .code-viewer { border: solid 1px silver; font-family: monospace; font-size: 12px; padding: 5px; background-color: white; margin-bottom: 10px; } .code-viewer-inner { width: 100%; border-top: solid 1px #E3E3E3; } .code-viewer .line .number { width: 40px; background-color: teal; color: white; border-bottom: solid 1px #E3E3E3; padding: 0px 5px 0px 5px; } .code-viewer .line .data { border-bottom: solid 1px #E3E3E3; white-space: pre-wrap; padding-left: 5px; } .code-viewer .action { padding: 0px 0px 5px 0px; } .code-viewer .action a { text-decoration: none; color: teal; font-family: Arial, sans-serif; font-size: 12px; font-weight: bold; margin: 0px 5px 0px 5px; } .code-viewer .action a:hover { text-decoration: underline; } .code-viewer .raw-code { display: none; } </style> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script> var cv_ids = new Array(); function cv_getId() { var id = 'E' + Math.floor(Math.random() * 100000); while (cv_ids.indexOf(id) >= 0) { id = 'E' + Math.floor(Math.random() * 100000); } cv_ids.push(id); return id; } function cv_process(esrc) { esrc = $(esrc); var src = esrc.html(); esrc.hide(); var id = cv_getId(); var id2 = cv_getId(); var id3 = cv_getId(); esrc.after("<div id='" + id + "' class='code-viewer'><div id='" + id2 + "' class='action'></div><table cellspacing='0' cellpadding='0' class='code-viewer-inner'></table><div id='" + id3 + "' class='raw-code'></div></div>"); var etag = $('#' + id + ' .code-viewer-inner'); var eaction = $('#' + id2); eaction.append("<a href='javascript:return false;' onclick=\"var e1 = $('#" + id + " .code-viewer-inner'); var e2 = $('#" + id3 + "'); e1.show(); e2.hide();\">formatted</a>"); eaction.append("<a href='javascript:return false;' onclick=\"var e1 = $('#" + id + " .code-viewer-inner'); var e2 = $('#" + id3 + "'); e2.show(); e1.hide();\">raw</a>"); var eraw = $('#' + id3); var lines = src.split('\n'); var src2 = ''; for (var i = 0; i < lines.length - 1; i++) { var line = lines[i]; line = line.replace(/\</g, '<'); line = line.replace(/\>/g, '>'); id = cv_getId(); etag.append("<tr id='" + id + "' class='line'></tr>"); var eline = $('#' + id); id = cv_getId(); id2 = cv_getId(); eline.append("<td id='" + id + "' class='number'></td><td id='" + id2 + "' class='data'></td>"); var enumber = $('#' + id); enumber.text(i + 1); var edata = $('#' + id2); edata.html(line); edata.css('white-space', 'pre-wrap'); edata.css('font-family', 'monospace'); src2 += line + '\n'; } eraw.append("<pre>" + src2 + "</pre>"); } var items = $('pre.code'); for (var i = 0; i < items.length; i++) { cv_process(items[i]); } </script>
No comments:
Post a Comment