vue3 tinymce 回车删除不用的br 标签
在Vue 3中使用TinyMCE编辑器时,如果你希望在用户按下回车键时自动删除或移除多余的
标签,你可以通过TinyMCE的配置来实现这一点。TinyMCE提供了多种配置选项来控制编辑器的行为,包括处理回车键的行为。
方法1:使用forced_root_block和force_p_newlines
你可以通过设置forced_root_block和force_p_newlines属性来控制段落和换行符的行为。例如,如果你想让TinyMCE在每个回车后创建一个新的p标签而不是br标签,你可以这样做:
tinymce.init({
selector: '#mytextarea',
forced_root_block: 'p',
force_p_newlines: true,
// 其他配置...
});
这样设置后,每次用户按下回车键,TinyMCE都会创建一个新的
标签而不是
标签。但是,如果你想要在特定情况下自动删除多余的
标签,你可能需要结合使用其他方法。
方法2:使用setup配置和自定义处理
另一种方法是使用TinyMCE的setup配置,在其中添加一个事件监听器来处理粘贴或按键事件,从而手动删除多余的
标签。例如,你可以监听keydown或ExecCommand事件:
tinymce.init({
selector: '#mytextarea',
setup: function(editor) {
editor.on('ExecCommand', function(e) {
if (e.command === 'mceInsertContent') {
const content = editor.getContent();
const cleanedContent = content.replace(/<br><br>/g, '<br>'); // 删除连续的<br>
editor.setContent(cleanedContent);
}
});
},
// 其他配置...
});
方法3:使用paste_preprocess和paste_postprocess
如果你希望在粘贴内容时自动处理多余的
标签,可以使用paste_preprocess或paste_postprocess事件:
tinymce.init({
selector: '#mytextarea',
paste_preprocess: function(plugin, args) {
args.content = args.content.replace(/<br><br>/g, '<br>'); // 删除连续的<br>
},
// 其他配置...
});
方法4:使用插件或外部库
还有一些外部库或插件可能提供更直接的方式来处理这种情况,例如使用一个自定义的插件或者利用现有的文本处理库(如DOMPurify)来清理HTML内容。例如,使用DOMPurify:
import DOMPurify from 'dompurify';
tinymce.init({
selector: '#mytextarea',
setup: function(editor) {
editor.on('ExecCommand', function(e) {
if (e.command === 'mceInsertContent') {
const content = editor.getContent();
const cleanedContent = DOMPurify.sanitize(content); // 使用DOMPurify清理内容
editor.setContent(cleanedContent);
}
});
},
// 其他配置...
});
通过上述方法之一,你可以在Vue 3中使用TinyMCE编辑器时控制和管理回车键产生的多余
标签。选择最适合你需求的方法来实现你的目标。