从 tinyMCE 中的插入符号位置删除 x 个字符 [英] Removing x number of characters from the caret position in tinyMCE
问题描述
我正在开发一个项目,用户可以在其中输入特殊字符,然后使用 Tab 键自动完成值.这部分主要工作,但我希望能够从插入符号位置之前删除 x 个字符.例如.如果 |
是插入符号并且我有以下文本 @chr|
.
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|
.
我希望能够删除光标位置之前的 3 个字符,例如我会以 @
结束.
I want to be able to delete 3 characters before the cursor position, e.g. I would just end up with @
.
我找到了一种使用以下代码获取当前光标位置的方法,但我找不到任何方法可以从该位置删除 x 个字符.
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;
}
推荐答案
您可以通过创建一个 范围 在当前插入符号位置结束:
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
要使用该演示,请将插入符号放在文本中的某个位置,然后单击顶部的删除 3"按钮以删除前面的 3 个字符.
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.
演示:http://codepen.io/anon/pen/dWVWYM?editors=0010
兼容IE9+
这篇关于从 tinyMCE 中的插入符号位置删除 x 个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!