如何在textarea中插入高亮文本,实现输入时自动删除选中高亮内容
textarea选中高亮文本输入自动替换实现方案
要实现和Stack Overflow插入代码按钮一致的交互,不需要写复杂的自定义事件监听,直接复用textarea原生能力就能完成:
- 触发插入操作时,先把预设的占位文本插入到当前光标位置
- 插入完成后调用
setSelectionRange接口,把刚插入的整段占位文本设为选中状态,此时文本会自动显示系统默认的选中高亮效果 - 不需要额外绑定keydown、input事件手动写删除逻辑:原生textarea默认就支持「选中状态下输入时,自动删除选中内容、用输入内容替换选中区域」的行为,交互和系统原生输入逻辑完全一致
最小实现代码
<textarea id="editor" rows="10" cols="50"></textarea> <button id="insertCodeBtn">点击插入代码块(对应大括号按钮效果)</button> <script> const editor = document.getElementById('editor'); const insertBtn = document.getElementById('insertCodeBtn'); insertBtn.addEventListener('click', () => { // 插入的占位提示文本 const placeholderText = '请输入代码内容'; // 记录当前光标选区位置 const cursorStart = editor.selectionStart; const cursorEnd = editor.selectionEnd; // 在光标位置插入占位文本 editor.value = editor.value.slice(0, cursorStart) + placeholderText + editor.value.slice(cursorEnd); // 选中刚插入的整段占位文本,自动触发高亮选中态 editor.selectionStart = cursorStart; editor.selectionEnd = cursorStart + placeholderText.length; // 焦点切回输入框,用户可直接输入 editor.focus(); }) </script>
不要自己额外实现选中删除逻辑,否则很容易和系统默认的选区操作、输入法输入行为冲突,复用原生能力的兼容性和交互流畅度是最好的。
内容的提问来源于stack exchange,提问作者giovnn
相关产品推荐
相关产品推荐

