我试图在一个可信的div内的插入位置从上下文菜单中选择后插入令牌。如果插入位置在一行中,我已设法做到这一点。
在我的情况下,只要出现其他HTML标签,即当线路发生变化时,范围偏移值将设置为0。我正在使用这两个函数来获取我在stackoverflow中找到的范围。
任何帮助表示赞赏!
function saveSelection() {
var range = null;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
return sel.getRangeAt(0);
}
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
}
我认为问题不在于你的元素中contenteditable
的内容。因为您正在使用contenteditable
div
的上下文菜单,如您所述。当你点击上下文菜单时,它将获得该上下文菜单的范围值。
因此,在单击某个菜单之前,应将范围值存储在某个变量上。
由于您的代码不完整,我无法将任何示例与您的代码相关联。
这是一个希望这将帮助您的例子:
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
<input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); ">
<div id="test" contenteditable="true">
Here is some nice text
</div>