You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript删除输入框光标前的字符

解决输入框删除光标前字符的问题

首先先搞懂字符串slice()方法的参数逻辑:

  • 第一个参数是截取起始位置(包含该位置的字符)
  • 第二个参数是截取结束位置(不包含该位置的字符),如果省略这个参数,就会从起始位置一直截取到字符串末尾;要是传负数,代表从字符串末尾往前数的位置(比如slice(0, -1)就是取到倒数第二个字符)

你之前的代码逻辑完全错了,slice(document.getElementById('input').selectionStart, 1)会从光标位置开始,试图截取到索引1的位置——如果光标位置比1大,这时候起始位置大于结束位置,slice会返回空字符串,自然达不到效果。

分两种情况给你正确代码:

1. 删除光标左侧紧邻的那个字符(和退格键效果一样)

const input = document.getElementById('input');
const cursorPos = input.selectionStart;
if (cursorPos > 0) {
  input.value = input.value.slice(0, cursorPos - 1) + input.value.slice(cursorPos);
  // 光标位置同步往前挪一位
  input.selectionStart = input.selectionEnd = cursorPos - 1;
}

2. 删除光标位置之前的所有字符

const input = document.getElementById('input');
input.value = input.value.slice(input.selectionStart);
// 光标移到输入框开头
input.selectionStart = input.selectionEnd = 0;

内容的提问来源于stack exchange,提问作者W4IT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 08:06:23