目前大多数相关项目实现的都是服务器端的Markdown语法解析,解析后将HTML代码返回给客户端,比如这个C#的项目: markdownsharp
我感觉这么轻量的格式没必要浪费服务器运算及带宽资源,还是通过Javascript实现客户端解析的方法最为实用,而且客户端解析的方式还能实现实时的所见即所得对照编辑,非常方便。
多番寻找和尝试,最终选定了 markdown-js
首先从这里下载其浏览器版:
https://github.com/evilstreak/markdown-js/releases
解压缩后在其js文件同目录下新建一个网页进行测试,代码如下:
<!DOCTYPE html><html> <body> <textarea id="text-input" oninput="this.editor.update()" rows="6" cols="60">Type **Markdown** here.</textarea> <div id="preview"> </div> <script src="markdown.js"></script> <script> function Editor(input, preview) { this.update = function () { preview.innerHTML = markdown.toHTML(input.value); }; input.editor = this; this.update(); } var $ = function (id) { return document.getElementById(id); }; new Editor($("text-input"), $("preview")); </script> </body></html>
这样就轻松的实现了实时解析转换:
转换后得到的只是最基础的HTML,可以用CSS美化一下,随手将Bootstarp的CSS引用过来看看:
<!DOCTYPE html><html><head><link href="http://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"></head> <body style="padding:30px"> <textarea id="text-input" oninput="this.editor.update()" rows="6" cols="60">Type **Markdown** here.</textarea> <div id="preview"> </div> <script src="markdown.js"></script> <script> function Editor(input, preview) { this.update = function () { preview.innerHTML = markdown.toHTML(input.value); }; input.editor = this; this.update(); } var $ = function (id) { return document.getElementById(id); }; new Editor($("text-input"), $("preview")); </script> </body></html>
这样看起来已经很不错了。
顺带来看一下转换后生成的HTML代码吧:
<div id="preview"><p><code>Type</code> <strong>Markdown</strong> here.</p><h1>测试</h1><hr><h3>开始</h3><blockquote><p>引用<br>12345</p></blockquote><ul><li>无序 </li><li>aa </li><li>ass<code>SDDS</code></li><li>33<em>1222</em>cccccccccccc</li></ul><p><a href="http://www.126.com">126邮箱</a></p><pre><code>代码块111111111111111111131111111111111111111111111111112222<>C<OC)(#838132@#!#*!$$</code></pre></div>
将此技术应用在博客或是CMS平台上会非常实用,也可以作为公告系统或私信系统使用。
这种方式的缺点在于SEO方面:搜索引擎可能无法了解页面内容的格式,像本该着重的标题的可能只会被当做普通内容一并处理,甚至还可能认为此内容是乱打的(那么多多余的符号~)。
联系客服