Insert HTML at the Cursor in a Contenteditable Div
When working with a contenteditable div, it is often necessary to insert HTML at the cursor position. This can be done using JavaScript to capture the keypress event and prevent the default behavior of the enter key.
To insert HTML, we can use the insertNode() method of the Range object. This method allows us to insert a node into the DOM at a specified location. In most browsers, except IE < 9, we can use this method directly.
Here's a function that demonstrates how to insert HTML at the cursor position in all major browsers, whether content is selected or not:
function pasteHtmlAtCaret(html, selectPastedContent) { var sel, range; if (window.getSelection) { // IE9 and non-IE sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); range.deleteContents(); // Create a document fragment to hold the HTML var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node, lastNode; while ( (node = el.firstChild) ) { lastNode = frag.appendChild(node); } // Insert the HTML into the document range.insertNode(frag); // Preserve the selection if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); if (selectPastedContent) { range.setStartBefore(firstNode); } else { range.collapse(true); } sel.removeAllRanges(); sel.addRange(range); } } } else if ( (sel = document.selection) && sel.type != "Control") { // IE < 9 var originalRange = sel.createRange(); originalRange.collapse(true); sel.createRange().pasteHTML(html); if (selectPastedContent) { range = sel.createRange(); range.setEndPoint("StartToStart", originalRange); range.select(); } } }
In IE < 9, we can use the pasteHTML() method of the Range object to insert HTML.
This method is more flexible, as it allows us to specify whether we want to select the inserted content or not.
To call this function, simply pass in the HTML that you want to insert and a boolean value to indicate whether or not to select the inserted content.
For example:
pasteHtmlAtCaret('New HTML
', true);The above is the detailed content of How do I insert HTML at the cursor position in a contenteditable div using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!