[英]Move caret position after focus() for ContentEditable <DIV>
我正在尝试用JavaScript创建一个非常基本的RTF编辑器,但是选择时遇到了问题。 因此,基本上,由于它是一个contentEditable <div>,因此每当用户从网页粘贴预先格式化的文本时,该格式就不会被剥夺。
一个容易破解的技巧是在按下Ctrl + V时将焦点放在<textarea>上,以便将文本粘贴到其中,然后onkeyup,将焦点返回到<div>,将内容复制过来并删除输入的内容到<textarea>。
这样很容易,但是当我将焦点放回到contentEditable&; t; div>上时,插入标记的位置在开始处,而不是紧接在粘贴之后。 我对选择知识不甚了解,无法弄清楚,因此,我希望获得一些帮助。 这是我的代码:
// Helpers to keep track of the length of the thing we paste, the cursor position
// and a temporary random number so we can mark the position.
editor_stuff =
{
cursor_position: 0,
paste_length: 0,
temp_rand: 0,
}
// On key up (for the textarea).
document.getElementById("backup_editor").onkeyup = function()
{
var main_editor = document.getElementById("question_editor");
var backup_editor = document.getElementById("backup_editor");
var marker_position = main_editor.innerHTML.search(editor_stuff.temp_rand);
// Replace the "marker" with the .value of the <textarea>
main_editor.innerHTML = main_editor.innerHTML.replace(editor_stuff.temp_rand, backup_editor.value);
backup_editor.value = "";
main_editor.focus();
}
// On key down (for the contentEditable DIV).
document.getElementById("question_editor").onkeydown = function(event)
{
key = event;
// Grab control + V end handle paste so "plain text" is pasted and
// not formatted text. This is easy to break with Edit -> Paste or
// Right click -> Paste.
if
(
(key.keyCode == 86 || key.charCode == 86) && // "V".
(key.keyCode == 17 || key.charCode == 17 || key.ctrlKey) // "Ctrl"
)
{
// Create a random number marker at the place where we paste.
editor_stuff.temp_rand = Math.floor((Math.random() * 99999999));
document.getElementById("question_editor").textContent += editor_stuff.temp_rand;
document.getElementById("backup_editor").focus();
}
}
所以我的想法是将光标位置(整数)存储在我的助手数组( editor_stuff.cursor_position
)中。
注意:我整天都在寻找其他答案,因此无法为我工作。
这是一个在插入符号位置插入文本的函数:
演示: http : //jsfiddle.net/timdown/Yuft3/2/
码:
function pasteTextAtCaret(text) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var textNode = document.createTextNode(text);
range.insertNode(textNode);
// Preserve the selection
range = range.cloneRange();
range.setStartAfter(textNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().text = text;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.