HTML内嵌Markdown编辑器

实现步骤
1、获取markdown的开源库,这里用的是开源项目showdown。
将showdown.min.js拷贝到项目中,需要的其他扩展可通过setOption(“扩展名”,true)去启动。

  • showdown: https://github.com/showdownjs/showdown

2、选择喜欢的Markdown样式,下载引用该css到自己的项目,还可以适当修改样式。

  • 李笑来老师的https://gist.github.com/xiaolai/aa190255b7dde302d10208ae247fc9f2
  • 少数派主题: https://cdn.sspai.com/sspai.css
  • Mweb主题: https://cdn.sspai.com/MWeb.css
  • Github主题: https://github.com/sindresorhus/github-markdown-css
  • typora主题合集下载: https://theme.typora.io/

3、按照showdown和选择的样式要求的格式来书写html文件。我这里用的是Github主题。
Github主题的使用方式:
在这里插入图片描述
showdown.min.js的使用方式:
在这里插入图片描述
其他扩展选项:
在这里插入图片描述
实现代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>html内嵌markdown</title>
    <script src="showdown.min.js"></script>
    <link rel="stylesheet" type="text/css" href="github-markdown.css">
</head>

<body>
    <style>
    #editor {
        display: flex;
        min-height: 600px;
        width: 100%;
    }

    #md-area {
        width: 100%;
        background: #f5f5f5;
        border: 1px solid #111;

    }
    #view-area {
        width: 100%;
        border: 1px solid #111;
    }
    
    /*Github主题要求的样式引入*/
    .markdown-body {
        box-sizing: border-box;
        min-width: 200px;
        max-width: 980px;
        margin: 0 auto;
        padding: 45px;
    }

    @media (max-width: 767px) {
        .markdown-body {
            padding: 15px;
        }
    }
    </style>

<div id="editor">
    <textarea id="md-area" onkeyup=mdConverter()></textarea>  <!-- 键盘每次点击实时调用 -->
    <article id="view-area" class="markdown-body">            <!-- github主题样式应用 -->
    </article>
</div>

<script>
    function mdConverter() {
        var md = document.getElementById("md-area").value;
        var converter = new showdown.Converter();  //增加拓展table
        converter.setOption('tables', true);  //启用表格选项。从showdown 1.2.0版开始,表支持已作为可选功能移入核心拓展,showdown.table.min.js扩展已被弃用
        var view = converter.makeHtml(md);
        document.getElementById("view-area").innerHTML = view;
    }
</script>
</body>
</html>

效果:
在这里插入图片描述

参考文章:https://www.jianshu.com/p/a57114bd9380
https://www.jianshu.com/p/7bb05fc9b7f0

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值