<div id="editor" contenteditable="true" style="border:1px solid #ccc; min-height:100px; padding:10px;"></div>
window.getSelection(), Range, document.createDocumentFragment()document.selection.createRange(), TextRange, pasteHTML()/**
* 在當前光標位置插入 HTML
* @param {string} html - 要插入的 HTML 字符串
*/
function insertHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9+、Firefox、Chrome、Safari、Opera
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents(); // 刪除選區內容(如有選中)
// 建立文檔片段,解析 HTML
var frag = document.createDocumentFragment();
var tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
var node, lastNode;
while ((node = tempDiv.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// 將光標移至插入內容之後
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);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ContentEditable 插入 Demo</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<style>
.editor { width:98%; min-height:80px; border:1px solid #000; padding:5px; font:14px/1.6 Arial; overflow-y:auto; }
.toolbar { margin:5px 0; }
.emoji-list { display:none; background:#f0f0f0; padding:5px; }
.emoji-list span { cursor:pointer; margin:0 5px; font-size:18px; }
</style>
</head>
<body>
<div class="toolbar">
<button id="btnBold">加粗</button>
<button id="btnEmoji">表情</button>
<div class="emoji-list" id="emojiPanel">
<span data-emoji="😀">😀</span>
<span data-emoji="😂">😂</span>
<span data-emoji="👍">👍</span>
</div>
</div>
<div id="editor" class="editor" contenteditable="true"></div>
<script>
var $editor = $('#editor');
// 1. 粗體
$('#btnBold').click(function() {
$editor.focus();
insertHtmlAtCaret('<b>粗體文字</b>');
});
// 2. 表情面板切換
$('#btnEmoji').click(function() {
$('#emojiPanel').toggle();
});
// 3. 表情插入(事件代理)
$('#emojiPanel').on('click', 'span', function() {
$editor.focus();
insertHtmlAtCaret($(this).data('emoji'));
$('#emojiPanel').hide();
});
// 核心插入函數(同上)
function insertHtmlAtCaret(html) { ... }
</script>
</body>
</html>
若需在失焦後恢復光標位置,可保存 Range 並用 selection.addRange() 恢復:
var savedRange = null;
$('#editor').on('focus', function() {
if (savedRange) {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(savedRange);
}
}).on('blur', function() {
var sel = window.getSelection();
if (sel.rangeCount) savedRange = sel.getRangeAt(0).cloneRange();
});
| 問題 | 原因 | 解決 |
|---|---|---|
| 插入後光標跳到開頭 | 未正確 collapse Range | 用 setStartAfter(lastNode) + collapse(true) |
| IE 插入無效 | 用錯 API | 判斷 document.selection 分支用 pasteHTML |
| 連續插入位置錯亂 | Selection 狀態未更新 | 每次插入後重新 removeAllRanges() + addRange() |