将插入符号位置移动到ContentEditable<DIV>
Move caret position after focus() for ContentEditable <DIV>
我正试图用JavaScript创建一个非常基本的富文本编辑器,但我在选择方面遇到了问题。所以基本上,因为它是一个contentEditable<div>,每当用户从网页粘贴预先格式化的文本时,格式不会被剥离。
一个容易破解的破解方法是将焦点放在<text区域>当按下Ctrl+V时,文本被粘贴到那里,然后在向上键时,将焦点放回<div>,复制内容并删除进入<text区域>。
所以这很容易,但当我把焦点放回内容Editable&;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
)中。
注意:我一整天都在SO上寻找其他答案,但都找不到。
这里有一个在插入符号位置插入文本的函数:
演示: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;
}
}
相关文章:
- 在<页眉>标签
- 添加文字和评论功能更新Div
- 如何更改<svg>标记为<img>用js标记
- Ckeditor-plugin:插入虚假元素add不情愿<p>标签前后
- Ajax文件加载和<输入>文件加载
- 点击后隐藏潜水?(但如果Div是一面旗帜呢?)
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- 使用JavaScript动态插入DIV的成本有多高
- 链接所有<a>Meteor
- 在<输入类型=“;文件“/>
- DIV并排,位置不正确
- Div根据<选择>菜单
- 将插入符号位置移动到ContentEditable<DIV>
- 正在转换<br>标记到<Div>或者<P>标签
- 如何在<Div类=“;abc定义“;style='显示“>或者在<Div类=“;aB-cd-e
- 如何将<DIV>标签,该标签来自AJAX
- 禁用& lt; img>在ie9中选择和调整可内容DIV的大小
- 仅重新加载<Div>不是整个形式
- 将函数绘制为<DIV>
- 当& lt; li>改变我们的Div类