我有以下方法在插入符号位置粘贴一些 HTML,使用 `range.insertNode(),源自 this SO answer
function insertAtCursor(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();
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);
}
}
} // non IE code removed
}
这适用于 Windows 应用商店应用。我发现了 a bug在 Windows 8.1 的通用应用程序中,在使用 range.insertNode()
粘贴事件后出现严重的打字滞后。该问题仅发生在 Windows 10 下运行的 Windows 8.1 通用应用程序中。我无法在 Windows 8.1 下复制该问题(尽管我过去肯定在 Win8.1 上遇到过它)-但每次在 Windows 10 上都会发生使用此示例应用程序的机器
有没有人知道另一种不使用 range.insertNode()
将 HTML 粘贴到插入符号的方法?使用 IE11 呈现引擎的 Windows 应用商店应用,因此如果它在 IE11 中工作,它将在商店应用/通用应用中工作
最佳答案
呵呵。我现在觉得有点傻。答案是我发布的链接中的第二个答案
var doc = document.getElementById("your_iframe").contentWindow.document;
// IE <= 10
if (document.selection){
var range = doc.selection.createRange();
range.pasteHTML("<b>Some bold text</b>");
// IE 11 && Firefox, Opera .....
}else if(document.getSelection){
var range = doc.getSelection().getRangeAt(0);
var nnode = doc.createElement("b");
range.surroundContents(nnode);
nnode.innerHTML = "Some bold text";
};
当我用这个 surroundContents
方法替换我的 insertNode
代码时,一切正常。现在我只需要 fork 我喜欢的富编辑器并替换方法
关于javascript - 在不使用 insertNode 的情况下在插入符处粘贴 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709313/