|
這個(gè)markdown格式轉(zhuǎn)html格式的開源JavaScript庫在github上的地址: https://github.com/millerblack/markdown-js 從markdown 格式轉(zhuǎn)成html源代碼格式 新建一個(gè)以js結(jié)尾的文件,將下列內(nèi)容粘貼進(jìn)去: var markdown = require( "markdown" ).markdown;console.log( markdown.toHTML( "Hello *World*!" ) );

用nodejs執(zhí)行,可以看到markdown格式的字符串: Hello World! 被自動(dòng)轉(zhuǎn)換成了html格式的字符串: <p>Hello <em>World</em>!</p> 
除了nodejs以外,我們還可以在瀏覽器里使用這個(gè)開源庫。 新建一個(gè)html,將下列源碼粘貼進(jìn)去: <!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="../node_modules/markdown/lib/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>

用瀏覽器打開這個(gè)html,在頂部輸入框里輸入markdown代碼后,能自動(dòng)調(diào)用這個(gè)開源庫,轉(zhuǎn)換成html源代碼,然后賦給innerHTML, 這樣我們?cè)赨I上能看到實(shí)時(shí)的markdown代碼轉(zhuǎn)html代碼的結(jié)果。 
要獲取更多Jerry的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙
|