点击按钮丢失文本选区,如何用JavaScript实现WYSWYG编辑器功能?
解决WYSWYG编辑器textarea选区点击按钮丢失的问题
你的核心问题是:点击按钮时textarea失去焦点,选区被清除,导致无法获取选中内容。而且window.getSelection()本来就不适用于textarea的内部选区——textarea的选区是独立维护的,要用它自身的selectionStart和selectionEnd属性来获取。
修正方案
- 实时保存textarea的选区状态
- 点击按钮时用保存的选区信息处理内容
完整代码如下:
// 获取textarea元素 const textarea = document.querySelector('textarea'); // 保存选区的起始和结束位置 let savedSelection = { start: 0, end: 0 }; // 监听textarea的选中事件,实时保存选区 textarea.addEventListener('select', function() { savedSelection.start = this.selectionStart; savedSelection.end = this.selectionEnd; }); // 绑定按钮点击事件 jQuery("#h").click(function() { // 跳过无选中内容的情况 if (savedSelection.start === savedSelection.end) return; const content = textarea.value; // 提取选中的文本 const selectedText = content.substring(savedSelection.start, savedSelection.end); // 包裹目标标签 const wrappedText = `<p class='n-h8'>${selectedText}</p>`; // 拼接新内容 const newContent = content.slice(0, savedSelection.start) + wrappedText + content.slice(savedSelection.end); // 更新textarea内容 textarea.value = newContent; // 可选:将光标定位到包裹内容的末尾,提升编辑体验 const newCursorPos = savedSelection.start + wrappedText.length; textarea.selectionStart = textarea.selectionEnd = newCursorPos; // 让textarea重新获得焦点 textarea.focus(); });
关键说明
- 不要用
window.getSelection()处理textarea选区:textarea、input这类表单元素的选区是独立于页面选区的,必须用自身的selectionStart/selectionEnd属性。 - 提前保存选区:因为点击按钮时textarea会失去焦点,选区会被清除,所以要在用户选中内容时(通过
select事件)实时保存选区位置。 - 可选的光标定位:处理完内容后让textarea重新聚焦并设置光标位置,能让编辑流程更顺畅。
内容的提问来源于stack exchange,提问作者Trts
相关产品推荐
相关产品推荐

