如何使用Javascript为textarea选中内容包裹[start][end]标签
功能实现方案
核心思路
- 不要用
window.getSelection(),该API仅适用于获取页面普通文本的选中范围,textarea作为表单控件,内部文本选中状态由自身独立属性维护 - 直接读取textarea的
selectionStart、selectionEnd属性获取选中内容的起止索引 - 拆分原文本为三部分:选中前的内容、选中内容、选中后的内容,拼接标签后重新赋值即可
- 可选操作:赋值后重置光标/选中范围,避免光标跳转到文本末尾
完整代码实现
function addTags() { // 获取textarea元素 const textarea = document.getElementById('user-input') // 存储原始内容 const originText = textarea.value // 获取选中起止位置 const start = textarea.selectionStart const end = textarea.selectionEnd // 未选中任何内容直接返回 if (start === end) return // 拼接新内容 const newText = originText.slice(0, start) + '[start]' + originText.slice(start, end) + '[end]' + originText.slice(end) // 赋值给textarea textarea.value = newText // 可选:将选中范围重置为包裹标签后的中间内容,方便用户后续操作 textarea.selectionStart = start + '[start]'.length textarea.selectionEnd = end + '[start]'.length // 可选:如果要把光标放在标签末尾,就写成textarea.selectionStart = textarea.selectionEnd = end + '[start][end]'.length }
效果验证
比如textarea内输入1 2 3,选中2后点击按钮,会直接生成1 [start]2[end] 3,和需求完全匹配。
内容的提问来源于stack exchange,提问作者coding_newbie
相关产品推荐
相关产品推荐

