如何监听Toast UI Editor的输入变更?
监听Toast UI Editor内容变更的解决方案
Toast UI Editor有自己的内置事件系统,不能直接用DOM元素的addEventListener方法监听内容变化,你可以通过编辑器实例的on()方法绑定change事件来实现需求:
- 先完成编辑器实例的初始化
- 调用
editor.on('change', callback)绑定内容变更事件,回调函数会在内容每次修改时触发
示例代码:
// 初始化编辑器 const editor = new toastui.Editor({ el: document.getElementById('editor-container'), initialEditType: 'markdown', // 可选markdown或wysiwyg模式 initialValue: '初始内容' }); // 监听内容实时变更 editor.on('change', function() { // 获取当前编辑器的markdown格式内容 const currentMarkdown = this.getMarkdown(); // 也可以获取HTML格式内容 const currentHtml = this.getHTML(); // 在这里编写你的内容变更处理逻辑 console.log('编辑器内容已更新:', currentMarkdown); });
如果需要模拟原生textarea仅在失焦时触发变更逻辑的场景,可以绑定blur事件:
editor.on('blur', function() { const content = this.getMarkdown(); console.log('编辑器失焦,当前内容:', content); });
内容的提问来源于stack exchange,提问作者dashingdove
相关产品推荐
相关产品推荐

