wangeditor——cdn引入的形式创建一个简易版编辑器——js技能提升

昨天同事那边有个需求,就是要实现聊天功能,需要用到一个富文本编辑器,参考如下:

上面的这个效果图是博客园的评论输入框

最终使用wangEditor编辑器实现的效果如下:

只保留了个别的菜单:

默认模式的wangEditor编辑器如下:

下面直接上代码:

解决步骤1:cdn引入

head头部标签引入css

js 复制代码
<link
      href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css"
      rel="stylesheet"
    />

script引入js

js 复制代码
 <script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>

解决步骤2:其余css配置

css 复制代码
<style>
      #editor---wrapper {
        border: 1px solid #ccc;
        z-index: 100; /* 按需定义 */
      }
      #toolbar-container {
        border-bottom: 1px solid #ccc;
      }
      #editor-container {
        height: 500px;
      }
    </style>

解决步骤3:html代码

js 复制代码
 <div id="editor-content-textarea"></div>
    <button id="btn-set-html">设置html</button>
    <div id="editor---wrapper" style="width: 900px">
      <div id="toolbar-container"><!-- 工具栏 --></div>
      <div id="editor-container"><!-- 编辑器 --></div>
    </div>

解决步骤4:script代码

js 复制代码
<script>
      const { createEditor, createToolbar } = window.wangEditor;

      const editorConfig = {
        placeholder: '请输入内容...',
        // maxLength:2000,//设置最大长度
        MENU_CONF: {},
        onChange(editor) {
          const html = editor.getHtml();
          console.log('editor content', html);
          // 也可以同步到 <textarea>
        },
      };

      const editor = createEditor({
        selector: '#editor-container',
        html: '<p><br></p>',
        config: editorConfig,
        mode: 'simple', // or 'simple'
      });

      const toolbarConfig = {
        excludeKeys: [
          'blockquote',
          'bgColor',
          // 'headerSelect',
          'italic',
          'group-more-style', // 排除菜单组,写菜单组 key 的值即可
          'bulletedList', //无序列表
          'numberedList', //有序列表
          'todo', //待办
          'emotion', //表情
          'insertTable', //表格
          'codeBlock', //代码块
          'group-video', //视频
          'divider', //分割线
          'fullScreen', //全屏
          // 'insertLink',//插入链接
          'group-justify', //对齐方式
          'group-indent', //缩进
          'fontSize', //字体大小
          'fontFamily', //字体
          'lineHeight', //行高
          'underline', //下划线
          'color', //颜色
          'undo', //撤销
          'redo', //重做
        ],
      };
      toolbarConfig.modalAppendToBody = true;

      // 创建 toolbar 和 editor

      // 可监听 `modalOrPanelShow` 和 `modalOrPanelHide` 自定义事件来设置样式、蒙层
      editor.on('modalOrPanelShow', (modalOrPanel) => {
        if (modalOrPanel.type !== 'modal') return;
        const { $elem } = modalOrPanel; // modal element

        // 设置 modal 样式(定位、z-index)
        // 显示蒙层
      });
      editor.on('modalOrPanelHide', () => {
        // 隐藏蒙层
      });
      const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
      });
      editorConfig.MENU_CONF['uploadImage'] = {
        server: '/api/upload-image',
        fieldName: 'custom-field-name',
        // 继续写其他配置...
        customInsert(res, insertFn) {
          console.log(res);
          // JS 语法
          // res 即服务端的返回结果
          // 从 res 中找到 url alt href ,然后插入图片
          //   "url": "xxx", // 图片 src ,必须
          // "alt": "yyy", // 图片描述文字,非必须
          // "href": "zzz" // 图片的链接,非必须
          insertFn(url, alt, href);
        },
        //【注意】不需要修改的不用写,wangEditor 会去 merge 当前其他配置
      };
});

如果要实现回显,则需要通过下面的代码

js 复制代码
// textarea 初始化值
      const textarea = document.getElementById('editor-content-textarea');
      textarea.value =
        '<p>wangEditor 只识别 editor.getHtml() 生成的 html 格式,不可以随意自定义 html 代码(html 格式太灵活了,不会全部兼容)</p>\n<p>wangEditor can only understand the HTML format from editor.getHtml() , but not all HTML formats.</p>\n<p><br></p>';

      // Set HTML
      document.getElementById('btn-set-html').addEventListener('click', () => {
        if (editor.isDisabled()) editor.enable();
        if (!editor.isFocused()) editor.focus();

        editor.select([]);
        editor.deleteFragment();

        window.wangEditor.SlateTransforms.setNodes(
          editor,
          { type: 'paragraph' },
          { mode: 'highest' }
        );
        editor.dangerouslyInsertHtml(textarea.value);

完整代码如下:

js 复制代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <title>富文本编辑器</title>
    <link
      href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css"
      rel="stylesheet"
    />
    <style>
      #editor---wrapper {
        border: 1px solid #ccc;
        z-index: 100; /* 按需定义 */
      }
      #toolbar-container {
        border-bottom: 1px solid #ccc;
      }
      #editor-container {
        height: 500px;
      }
    </style>
  </head>
  <body>
    <div id="editor-content-textarea"></div>
    <button id="btn-set-html">设置html</button>
    <div id="editor---wrapper" style="width: 900px">
      <div id="toolbar-container"><!-- 工具栏 --></div>
      <div id="editor-container"><!-- 编辑器 --></div>
    </div>
    <script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
    <script>
      const { createEditor, createToolbar } = window.wangEditor;

      const editorConfig = {
        placeholder: '请输入内容...',
        // maxLength:2000,//设置最大长度
        MENU_CONF: {},
        onChange(editor) {
          const html = editor.getHtml();
          console.log('editor content', html);
          // 也可以同步到 <textarea>
        },
      };

      const editor = createEditor({
        selector: '#editor-container',
        html: '<p><br></p>',
        config: editorConfig,
        mode: 'simple', // or 'simple'
      });

      const toolbarConfig = {
        excludeKeys: [
          'blockquote',
          'bgColor',
          // 'headerSelect',
          'italic',
          'group-more-style', // 排除菜单组,写菜单组 key 的值即可
          'bulletedList', //无序列表
          'numberedList', //有序列表
          'todo', //待办
          'emotion', //表情
          'insertTable', //表格
          'codeBlock', //代码块
          'group-video', //视频
          'divider', //分割线
          'fullScreen', //全屏
          // 'insertLink',//插入链接
          'group-justify', //对齐方式
          'group-indent', //缩进
          'fontSize', //字体大小
          'fontFamily', //字体
          'lineHeight', //行高
          'underline', //下划线
          'color', //颜色
          'undo', //撤销
          'redo', //重做
        ],
      };
      toolbarConfig.modalAppendToBody = true;

      // 创建 toolbar 和 editor

      // 可监听 `modalOrPanelShow` 和 `modalOrPanelHide` 自定义事件来设置样式、蒙层
      editor.on('modalOrPanelShow', (modalOrPanel) => {
        if (modalOrPanel.type !== 'modal') return;
        const { $elem } = modalOrPanel; // modal element

        // 设置 modal 样式(定位、z-index)
        // 显示蒙层
      });
      editor.on('modalOrPanelHide', () => {
        // 隐藏蒙层
      });
      const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
      });
      editorConfig.MENU_CONF['uploadImage'] = {
        server: '/api/upload-image',
        fieldName: 'custom-field-name',
        // 继续写其他配置...
        customInsert(res, insertFn) {
          console.log(res);
          // JS 语法
          // res 即服务端的返回结果
          // 从 res 中找到 url alt href ,然后插入图片
          //   "url": "xxx", // 图片 src ,必须
          // "alt": "yyy", // 图片描述文字,非必须
          // "href": "zzz" // 图片的链接,非必须
          insertFn(url, alt, href);
        },
        //【注意】不需要修改的不用写,wangEditor 会去 merge 当前其他配置
      };
      // textarea 初始化值
      const textarea = document.getElementById('editor-content-textarea');
      textarea.value =
        '<p>wangEditor 只识别 editor.getHtml() 生成的 html 格式,不可以随意自定义 html 代码(html 格式太灵活了,不会全部兼容)</p>\n<p>wangEditor can only understand the HTML format from editor.getHtml() , but not all HTML formats.</p>\n<p><br></p>';

      // Set HTML
      document.getElementById('btn-set-html').addEventListener('click', () => {
        if (editor.isDisabled()) editor.enable();
        if (!editor.isFocused()) editor.focus();

        editor.select([]);
        editor.deleteFragment();

        window.wangEditor.SlateTransforms.setNodes(
          editor,
          { type: 'paragraph' },
          { mode: 'highest' }
        );
        editor.dangerouslyInsertHtml(textarea.value);
      });
    </script>
  </body>
</html>
相关推荐
Evand J34 分钟前
【MATLAB例程】基于USBL和DVL的线性回归误差补偿,对USBL和DVL导航数据进行相互补偿,提高定位精度,附代码下载链接
开发语言·matlab·线性回归·水下定位·usbl·dvl
小蕾Java1 小时前
【VSCode】Visual Studio Code 2025安装包及安装教程 (附所有版本下载)
ide·vscode·编辑器
爱喝白开水a1 小时前
LangChain 基础系列之 Prompt 工程详解:从设计原理到实战模板_langchain prompt
开发语言·数据库·人工智能·python·langchain·prompt·知识图谱
Neverfadeaway2 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
武子康2 小时前
Java-152 深入浅出 MongoDB 索引详解 从 MongoDB B-树 到 MySQL B+树 索引机制、数据结构与应用场景的全面对比分析
java·开发语言·数据库·sql·mongodb·性能优化·nosql
杰克尼2 小时前
JavaWeb_p165部门管理
java·开发语言·前端
EndingCoder2 小时前
WebSocket实时通信:Socket.io
服务器·javascript·网络·websocket·网络协议·node.js
达子6662 小时前
用Vscode编译正点原子ESP32例程报错:ninja: error: loading ‘build.ninja‘: 系统找不到指定的文件
ide·vscode·编辑器
我胡为喜呀2 小时前
Vue3 中的 watch 和 watchEffect:如何优雅地监听数据变化
前端·javascript·vue.js
一成码农2 小时前
JavaSE面向对象(下)
java·开发语言