问题描述
< p>< p>如何使用jquery或其他插入HTML在我的contenteditable div的光标/ ; div contenteditable =true> Hello world< / div>
例如,如果光标/插入符号介于hello和world之间,然后用户点击一个按钮,例如插入图片,然后使用javascript,像< img src = etc etc>
之类的东西插入到hello和world之间。我希望我已经明确了这一点= S $ / B
$ b
示例代码将非常感谢,非常感谢!
以下函数将在所有主流桌面浏览器的光标位置插入一个DOM节点(元素或文本节点):
函数insertNodeAtCursor(node){
var sel,range,html;
if(window.getSelection){
sel = window.getSelection();
if(sel.getRangeAt&& sel.rangeCount){
sel.getRangeAt(0).insertNode(node);
}
} else if(document.selection&& document.selection.createRange){
range = document.selection.createRange();
html =(node.nodeType == 3)? node.data:node.outerHTML;
range.pasteHTML(html);
$ b如果你宁愿插入一个HTML字符串: p>
function insertHtmlAtCursor(html){
var sel,range,node;
if(window.getSelection){
sel = window.getSelection();
if(sel.getRangeAt&& sel.rangeCount){
range = window.getSelection()。getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
}
} else if(document.selection&& document.selection.createRange){
document.selection.createRange()。pasteHTML(html);
}
}
我已将此从我的答案改编为类似问题:
How can I (using jquery or other) insert html at the cursor/caret position of my contenteditable div:
<div contenteditable="true">Hello world</div>
For example, if the cursor/caret was between "hello" and "world" and the user then clicked a button, eg "insert image", then using javascript, something like <img src=etc etc>
would be inserted between "hello" and "world". I hope I've made this clear =S
Example code would be greatly appreciated, thanks a lot!
解决方案 The following function will insert a DOM node (element or text node) at the cursor position in all the mainstream desktop browsers:
function insertNodeAtCursor(node) {
var sel, range, html;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
sel.getRangeAt(0).insertNode(node);
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
html = (node.nodeType == 3) ? node.data : node.outerHTML;
range.pasteHTML(html);
}
}
If you would rather insert an HTML string:
function insertHtmlAtCursor(html) {
var sel, range, node;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
}
}
I've adapted this from my answer to a similar question: How to find cursor position in a contenteditable DIV?
这篇关于Contenteditable文本编辑器和光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!