TinyMCE - How to add a button that wraps selected text with a tag

前端 未结 2 1755
灰色年华
灰色年华 2021-02-02 00:02

I\'m currently using TinyMCE and would like to add a custom button that works as follows:

  1. User highlights text in the text-editior
  2. User clicks the custom
相关标签:
2条回答
  • 2021-02-02 00:25

    A better way to achieve this is to (1) perform a quick check to make sure the selection isn't empty, then (2) use the execCommand() method.

    Using execCommand() means the action will be available to undo. @Warrior's answer uses setContent() which will not be undoable.

    ed.addButton('mybutton', {
      title: 'My button', 
      class: 'MyCoolBtn', 
      image: 'MyCoolBtn.png', 
      onclick: function() { 
        ed.focus();
        var text = ed.selection.getContent({'format': 'html'});
        if(text && text.length > 0) {
          ed.execCommand('mceInsertContent', false, '<tag>'+text+'</tag>');
        }
      }
    });
    
    0 讨论(0)
  • 2021-02-02 00:32
    ed.addButton('mybutton', {
      title: 'My button', 
      class: 'MyCoolBtn', 
      image: 'MyCoolBtn.png', 
      onclick: function() { 
        // Add your own code to execute something on click 
        ed.focus();
        ed.selection.setContent('<tag>' + ed.selection.getContent() + '</tag>');
      }
    });
    
    0 讨论(0)
提交回复
热议问题