![](/img/trans.png)
[英]How to detect cursor position in contenteditable div and insert text at that position
[英]How to insert new <div> on a button click at the cursor position of existing <div>
this.$el.find('#divname').append(newDivHtml)
會將newDivHTML
附加到現有的div
中。 但是,我正在研究這種情況:
div1
用戶編輯一些自由文本並單擊一個按鈕newDivHtml
插入底層div1
的光標位置。我試過了:http: //jsfiddle.net/jwvha/1/
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);
}
}
2. doesn't seems to work for that.$e1.find('#sectionContentSimple').insertAdjacentHTML(100, newhtml);
只是一個沒有深入研究代碼的想法,您是否嘗試過將單擊的元素保存到變量中以便以后可以訪問它,而不是依靠它來保持焦點?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.