首页 > 技术文章 > 在网页上添加makedown编辑器

ellen-mylife 2019-07-06 17:09 原文

在做项目是需要有makedown写文件的功能,之前没有接触过,今天学习了下,在这里记录

参考

支持浏览器:支持浏览器: chrome/safari/firefox/ie9+

1.在浏览器集成 Mditor

引入Mditor 样式和脚本

<link rel="stylesheet" href="your-path/dist/css/mditor.min.css" />
<script src="your-path/dist/js/mditor.min.js"></script>

或者CDN资源

<link rel="stylesheet" href="https://unpkg.com/mditor@1.0.5/dist/css/mditor.min.css" />
...
<script src="https://unpkg.com/mditor@1.0.5/dist/js/mditor.min.js"></script>
...

我最开始是将CDN资源拷贝到css和js文件里使用,但是会有一些东西加载不出来,所以我最后还是老老实实按要求来了

2.添加textare元素

<textarea name="editor" id="editor"></textarea>

3.创建Mditor实例

var mditor =  Mditor.fromTextarea(document.getElementById('editor'));
 
//获取或设置编辑器的值
mditor.on('ready',function(){
  console.log(mditor.value);
  mditor.value = '** hello **';    
});

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>makedown编辑1</title>
    <link rel="stylesheet" href="https://unpkg.com/mditor@1.0.5/dist/css/mditor.min.css"/>
    <script src="https://unpkg.com/mditor@1.0.5/dist/js/mditor.min.js"></script>
    <script type="text/javascript">
    
        window.onload=function(){
            var mditor =  Mditor.fromTextarea(document.getElementById('editor'));

        mditor.on('ready',function(){
              console.log(mditor.value);
              mditor.value = '** hello **';    
        });
                
        }

        function submittext(){
            
            var text=document.getElementById('editor').value;
            console.log(text);
        }
        
    </script>
</head>
<body>
<div style="width:600px; height:600px;">
<textarea name="editor" id="editor"></textarea>
</div>
<button onclick="submittext()">提交</button>
</body>

</html>

但是这个时候会出现问题

Cannot read property 'style' of null

这是因为在加载JS的时候HTML没有被解析,JS代码找不到页面上的元素,所以也解析不了style,将JS代码放在HTML页面代码后面就好了

最终代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>makedown编辑1</title>
    <link rel="stylesheet" href="https://unpkg.com/mditor@1.0.5/dist/css/mditor.min.css"/>
    <script src="https://unpkg.com/mditor@1.0.5/dist/js/mditor.min.js"></script>
    
</head>
<body>
<div style="width:600px; height:600px;">
<textarea name="editor" id="editor"></textarea>
</div>
<button onclick="submittext()">提交</button>
</body>
<script type="text/javascript">
    
        window.onload=function(){
            var mditor =  Mditor.fromTextarea(document.getElementById('editor'));

        mditor.on('ready',function(){
              console.log(mditor.value);
              mditor.value = '** hello **';    
        });
                
        }

        function submittext(){
            //mditor.editor.insertBeforeText('文本');
            var text=document.getElementById('editor').value;
            console.log(text);
        }
        
    </script>
</html>

这个代码可以直接拷贝使用看效果,还有一些扩展的方法,可以看看我的参考

 

推荐阅读