咨询TinyMCE编辑器按空格自动生成列表无需按回车的实现方案
可以通过给TinyMCE添加自定义键盘事件监听的方式实现空格触发自动列表转换,无需按下回车,修改后的初始化配置如下:
<div id="notice"></div> <script> tinymce.init({ selector: '#notice', inline: true, menubar: false, skin: "oxide-dark", toolbar: 'bold italic bullist', plugins: ['lists','autoresize','textpattern'], toolbar_location: 'bottom', deprecation_warnings: false, // 新增自定义监听配置 setup: function(editor) { // 监听空格输入,触发列表转换 editor.on('keydown', function(e) { if (e.key === ' ') { const currentLineText = editor.selection.getNode().textContent.trimStart(); // 匹配行首为减号的格式 if (/^-\s*$/.test(currentLineText)) { e.preventDefault(); // 转成无序列表 editor.execCommand('InsertUnorderedList'); // 清空行首的减号占位符 editor.selection.setContent(''); } } }); // 可选优化:避免回车生成多余空列表项 editor.on('keydown', function(e) { if (e.key === 'Enter' && editor.queryCommandState('InsertUnorderedList')) { const currentLi = editor.selection.getNode().closest('li'); if (currentLi && currentLi.textContent.trim() === '') { e.preventDefault(); // 空列表项按回车直接退出列表模式 editor.execCommand('InsertUnorderedList'); editor.selection.setContent(''); } } }); } }); </script>
配置完成后的效果:
- 输入
-后按下空格,当前行将直接转换为无序列表项,不需要按下回车触发 - 可选优化逻辑生效后,如果在空的列表项中按下回车,会直接退出列表编辑模式,不会生成多余的空列表项,无需手动删除
内容的提问来源于stack exchange,提问作者Trombone0904
相关产品推荐
相关产品推荐

