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

时间:2009-12-10 03:13:44

标签: jquery tinymce

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

  1. 用户突出显示text-editior中的文字
  2. 用户点击自定义按钮X
  3. 文字(狗散步)用标签包裹(狗散步)
  4. 有关是否可以这样做的任何想法?我已经弄清楚如何使自定义按钮注入文本,但不包装文本...这是当前的代码:

    // 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('<strong>Hello world!</strong>');
        }
    });
    

    谢谢!

2 个答案:

答案 0 :(得分:30)

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

答案 1 :(得分:8)

更好的方法是(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, '<tag>'+text+'</tag>');
    }
  }
});
相关问题