| 2922 | |
| 2923 | // 智能插入HTML内容的函数 |
| 2924 | function insertHTMLAtCursor(html) { |
| 2925 | // 先尝试获取当前选区 |
| 2926 | const selection = window.getSelection(); |
| 2927 | let range = null; |
| 2928 | |
| 2929 | // 检查是否有选区且选区在编辑器内 |
| 2930 | if (selection && selection.rangeCount > 0) { |
| 2931 | const currentRange = selection.getRangeAt(0); |
| 2932 | const container = currentRange.commonAncestorContainer; |
| 2933 | |
| 2934 | // 检查选区是否在编辑器内部或编辑器元素本身 |
| 2935 | if (editor.contains(container) || container === editor) { |
| 2936 | range = currentRange; |
| 2937 | } |
| 2938 | } |
| 2939 | |
| 2940 | // 如果没有有效选区或选区不在编辑器内,在编辑器末尾插入 |
| 2941 | if (!range) { |
| 2942 | // 然后在编辑器末尾创建一个新的选区 |
| 2943 | range = document.createRange(); |
| 2944 | |
| 2945 | if (editor.childNodes.length === 0) { |
| 2946 | // 空编辑器,创建一个文本节点作为插入点 |
| 2947 | const textNode = document.createTextNode(''); |
| 2948 | editor.appendChild(textNode); |
| 2949 | range.setStart(textNode, 0); |
| 2950 | range.setEnd(textNode, 0); |
| 2951 | } else { |
| 2952 | // 在最后一个子节点后面设置选区 |
| 2953 | const lastChild = editor.lastChild; |
| 2954 | if (lastChild.nodeType === Node.TEXT_NODE) { |
| 2955 | range.setStart(lastChild, lastChild.textContent.length); |
| 2956 | range.setEnd(lastChild, lastChild.textContent.length); |
| 2957 | } else { |
| 2958 | range.setStartAfter(lastChild); |
| 2959 | range.setEndAfter(lastChild); |
| 2960 | } |
| 2961 | } |
| 2962 | } |
| 2963 | |
| 2964 | // 使用DOM操作插入HTML内容 |
| 2965 | try { |
| 2966 | // 创建HTML元素 |
| 2967 | const tempDiv = document.createElement('div'); |
| 2968 | tempDiv.innerHTML = html; |
| 2969 | |
| 2970 | // 使用Range.insertNode精确插入 |
| 2971 | const fragment = document.createDocumentFragment(); |
| 2972 | while (tempDiv.firstChild) { |
| 2973 | fragment.appendChild(tempDiv.firstChild); |
| 2974 | } |
| 2975 | |
| 2976 | // 清除选区内容(如果有选中内容) |
| 2977 | range.deleteContents(); |
| 2978 | |
| 2979 | // 插入新内容 |
| 2980 | range.insertNode(fragment); |
| 2981 | |