Removing x number of characters from the caret position in tinyMCE

折月煮酒 提交于 2019-12-12 04:47:33

问题


I am working on a project where the user can enter a special character and then tab to auto complete the values. This part is mostly working, but I want to be able to delete x number of characters from before the caret position. E.g. if | is the caret and I have the following text @chr|.

I want to be able to delete 3 characters before the cursor position, e.g. I would just end up with @.

I have found a way to get the current cursor position using the below code, but I haven't been able to find any way of being able to delete x number of characters from that position.

  function getCaretPosition()
        {
            var ed = tinyMCE.get('txtComment');     // get editor instance
            var range = ed.selection.getRng().startOffset;     // get range
            return range;
        }

回答1:


You can do this by creating a Range ending at the current caret position:

var ed = tinyMCE.get("mce_0"); // get editor instance
var editorRange = ed.selection.getRng(); // get range object for the current caret position

var node = editorRange.commonAncestorContainer; // relative node to the selection

range = document.createRange(); // create a new range object for the deletion
range.selectNodeContents(node);
range.setStart(node, editorRange.endOffset - 3); // current caret pos - 3 
range.setEnd(node, editorRange.endOffset); // current caret pos
range.deleteContents();

ed.focus(); // brings focus back to the editor

To use the demo, position the caret somewhere in the text and then click the "Remove 3" button at the top to delete the preceding 3 characters.

Note that my demo is simplified and doesn't do any bounds checking.

Demo: http://codepen.io/anon/pen/dWVWYM?editors=0010

Compatibility is IE9+



来源:https://stackoverflow.com/questions/43736011/removing-x-number-of-characters-from-the-caret-position-in-tinymce

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!