TinyMCE – 如何添加一个用标签包装所选文本的按钮

我目前正在使用TinyMCE,并希望添加一个按如下方式工作的自定义按钮:

  1. 用户突出显示text-editior中的文本
  2. 用户单击自定义按钮X.
  3. 文字(狗散步)用标签包裹(狗散步)

关于是否可以这样做的任何想法? 我已经弄清楚如何使自定义按钮注入文本,但不包装文本…这是当前的代码:

// Add a custom button ed.addButton('mybutton', { title : 'My button', 'class' : 'MyCoolBtn', image : 'MyCoolBtn.png', onclick : function() { // Add you own code to execute something on click ed.focus(); ed.selection.setContent('Hello world!'); } }); 

谢谢!

 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('' + ed.selection.getContent() + ''); } }); 

更好的方法是(1)执行快速检查以确保选择不为空,然后(2)使用execCommand()方法。

使用execCommand()表示可以撤消操作。 @ Warrior的答案使用了setContent() ,它不可撤销。

 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, ''+text+''); } } });