将基本样式应用于 TinyMce 中的不可编辑元素

Tim*_*nin 6 html javascript tinymce tinymce-4

语境:

TinyMce 有一个不可编辑的插件,允许使元素不可编辑。如果元素具有mceNonEditable该类,则 TinyMce 将使该元素不可编辑。

问题:

我希望能够用基本的样式标签包装这个不可编辑的元素。

例如,如果我有:

Hello <span class="mceNonEditable">user_name</span> how are you today ?
Run Code Online (Sandbox Code Playgroud)

如果我单击user_name以选择不可编辑的跨度并单击TinyMce Blod 按钮

在此处输入图片说明

我希望结果是:

Hello <b><span class="mceNonEditable">user_name</span></b> how are you today ? 
Run Code Online (Sandbox Code Playgroud)

但取而代之的是,什么也没有发生。当我单击TinyMce Blod 按钮时,代码不会更改。

我创建了一个小的 jsFiddle 来演示这一点:https ://jsfiddle.net/timotheejeannin/2hhpenm5/

我试过的:

我真的希望你能帮忙!

And*_*w H 5

我想出了一个“稍微”不那么hacky的方法来做到这一点。本质上,我注册了一个“BeforeExecCommand”事件,对于某些事件,它删除了 contenteditable 属性,允许命令运行,并在“ExecCommand”事件中读取 contenteditable false 属性。这样做使我不必自定义处理我在其他提议的解决方案中看到的各种可能的事件。我已经分叉了您的原始示例来演示解决方案(并添加了几个额外的格式选项和“变量”功能),可以在这里找到:https : //jsfiddle.net/hunterae/8fsnv3h6/40/

以下是解决方案中最相关的部分:

tinymce.init({
  // Additional options here
  setup: function (editor) {
    var $ = tinymce.dom.DomQuery;
    var nonEditableClass = editor.getParam('noneditable_noneditable_class', 'mceNonEditable');
    // Register a event before certain commands run that will turn contenteditable off temporarilly on noneditable fields
    editor.on('BeforeExecCommand', function (e) {
      // The commands we want to permit formatting noneditable items for
      var textFormatCommands = [
        'mceToggleFormat',
        'mceApplyTextcolor',
        'mceRemoveTextcolor'
      ];
      if (textFormatCommands.indexOf(e.command) !== -1) {
        // Find all elements in the editor body that have the noneditable class on them
        //  and turn contenteditable off  
        $(editor.getBody()).find('.' + nonEditableClass).attr('contenteditable', null);
      }
    });
    // Turn the contenteditable attribute back to false after the command has executed
    editor.on('ExecCommand', function (e) {
        // Find all elements in the editor body that have the noneditable class on them
      //  and turn contenteditable back to false
      $(editor.getBody()).find('.' + nonEditableClass).attr('contenteditable', false);
    });
  },
  init_instance_callback: function (editor) {

    /* 
        The following two hacks fix some weirdness with the way the textcolor
      plugin works - namely, it was attemping to apply color and background-color
      directly on the element that had the noneditable css class on it instead of putting
      a span around it as underline does.
    */
    editor.formatter.get('forecolor')[0].exact = true;
    editor.formatter.get('hilitecolor')[0].exact = true;


  }
});
Run Code Online (Sandbox Code Playgroud)


Mic*_*min 0

我相信您可以使用一个简单的自定义工具栏按钮来完成此操作,您可以将其添加到您的 TinyMCE 配置中。

当您单击不可编辑元素时,您实际上会获得一个 DOM 节点,它是整个不可编辑元素。然后,您绝对可以使用 DOM 操作向该元素添加样式或将该元素包装在另一个标签中。例如,请参阅此 TinyMCE Fiddle:

http://fiddle.tinymce.com/sDfaab

当您单击不可编辑元素并单击Add Style to Node按钮时,您会注意到整个不可编辑元素将获得一个新的内联样式,该样式将文本加粗。