我正在使用 jHtmlArea,但我想这个问题与使用 iframe/文档编辑模式运行的任何 html 文本框相关。
使用 pasteHTML 函数将一些文本设置到 jHtmlArea 中后,我想将光标放在我插入的文本之后,有没有好的方法可以做到这一点?
最佳答案
我建议将 jHtmlArea 的 pasteHTML
实现替换为不使用浏览器嗅探、在浏览器之间表现一致并在插入内容后放置插入符的有能力的实现。类似以下内容,改编 self 在这里的回答:Insert html at caret in a contenteditable div
jHtmlArea.prototype.pasteHTML = function(html) {
var sel, range, iframe = this.iframe[0],
win = iframe.contentWindow || iframe.contentDocument.defaultView,
doc = win.document;
win.focus();
if (win.getSelection) {
// IE9 and non-IE
sel = win.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = doc.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 ( (sel = doc.selection) && sel.type != "Control") {
// IE < 9
sel.createRange().pasteHTML(html);
}
}
关于Javascript - jHtmlArea,设置光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8150212/