问题描述
我实现了一个过程,用户可以从div中选择一个选项,然后将其插入到内容可编辑div中。
要实现这一点,首先我将选择范围保存在可编辑div的mouseup和keyup事件上。
当用户单击div的选项之一时,它将恢复选择范围,将文本插入保存的位置,并将插入标记移动到插入文本的末尾。另外,我再次保存新的插入符位置,以防用户单击另一个选项,在之前添加的文本旁边插入新文本。
它在IE11之外的所有浏览器中都可以正常工作。当用户单击div多次以插入文本时,第一个值将替换为新值,而不是在第一个插入的文本之后插入。
似乎selection.collapsetoEnd()
在IE11中不能很好地工作。
谢谢。
JSfiddle:https://jsfiddle.net/7k1rt82s/4/
代码:
HTML
<div id="insert-text-div" style="border-style: solid; width: 100px;cursor: pointer;">Option DIV</div>
<div id="editor" contenteditable="true" style="border-style: solid; height: 150px;">Please click on the option div to add a dummy text.</div>
JS
var selectedRange;
$( "#editor" ).on('mouseup keyup',function() {
// Save selection
var selection = window.getSelection();
if (selection.getRangeAt && selection.rangeCount) {
selectedRange = selection.getRangeAt(0);
}
});
$('#insert-text-div').on('click',function() {
if (!selectedRange) return;
// Get the current selection and set the selection range stored in the Editor mouseup / keyup event
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(selectedRange);
// Insert the text into the range
var range = selection.getRangeAt(0);
range.deleteContents();
var textNode = document.createTextNode("DummyText");
range.insertNode(textNode);
// Move the caret to the end of the added text
selection.collapsetoEnd();
// Save the selection in case the user immediately inserts another text
$('#editor').trigger('keyup');
});
解决方法
我从MDN找到了兼容性表,这是推荐使用的资源。提到了Internet Explorer不知道crashToEnd函数的兼容性。
https://developer.mozilla.org/en-US/docs/Web/API/Selection/collapseToEnd。
此外,该问题可能来自null范围,您可能会在注释中查找更深的地方。
https://w3c.github.io/selection-api/#background 注意 请参见错误15470。IE9,Firefox 12.0a1,Chrome 17开发者和Opera Next 12.00 alpha都使该范围最初为空。