TinyMCE编辑器如何选中不可编辑自定义占位符并应用文本格式
解决方案
你可以通过TinyMCE事件配置+CSS配合的方式实现需求,无需修改contenteditable="false"属性,既保证占位符内容不可修改,又能选中整块应用格式:
- 给占位符元素添加可选中样式,在TinyMCE的自定义内容CSS中加入以下规则:
.placeholderClass { user-select: all; -webkit-user-select: all; cursor: pointer; } /* 适配编辑器默认选中高亮效果 */ .mce-content-body .placeholderClass::selection { background-color: #b4d5ff; }
- 调整TinyMCE初始化配置,添加选中拦截和格式应用逻辑:
tinymce.init({ selector: '你的编辑器选择器', // 引入官方noneditable插件辅助处理不可编辑元素 plugins: 'noneditable', // 指定占位符类为不可编辑类,插件会自动禁止内容修改 noneditable_noneditable_class: 'placeholderClass', setup: function (editor) { // 点击占位符时自动选中整块元素 editor.on('click', function (e) { if (e.target.closest('.placeholderClass')) { const placeholderEl = e.target.closest('.placeholderClass'); const range = editor.dom.createRng(); range.selectNode(placeholderEl); editor.selection.setRng(range); } }); // 处理粗体、斜体、下划线等格式应用 editor.on('BeforeExecCommand', function (e) { const selectedNode = editor.selection.getNode(); const cmd = e.command.toLowerCase(); if (selectedNode.classList.contains('placeholderClass') && ['bold', 'italic', 'underline'].includes(cmd)) { e.preventDefault(); // 映射格式对应标签 const tagMap = { 'bold': 'strong', 'italic': 'em', 'underline': 'u' }; // 给占位符外层包裹格式标签 editor.dom.wrap(selectedNode, `<${tagMap[cmd]}>`); } }); } });
- 原有占位符HTML结构无需改动,保留
contenteditable="false"和data-mce-selected="1"属性即可:
<span contenteditable="false" class="placeholderClass" data-mce-selected="1">Placeholder<i id="removePlaceholder"></i> </span>
内容的提问来源于stack exchange,提问作者user3478639
相关产品推荐
相关产品推荐

