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

移动端JavaScript监听contenteditable元素退格键事件异常问题求助

移动端JavaScript监听contenteditable元素退格键事件异常问题求助

我最近做了个小功能:用带有contenteditable="true"的<span>作为输入区域,通过onkeydown事件生成包含按键字符的新元素,同时调用preventDefault()避免按键字符直接显示在输入框里;当按下退格键时,就删除最后生成的那个元素。

这个功能在桌面浏览器上运行完全正常,但在移动端遇到了奇怪的问题:测试Firefox for Android时,我输入几个字母后按退格键,JS里的事件根本没触发!不管是用系统默认虚拟键盘还是Swiftkey,键盘都会先“缓存”最后输入的那些字母,只有把这些键盘层面的字母都删完之后,退格事件才会传递到JS代码里。

这个问题真的有点难用文字说清楚,核心就是只在移动端出现这个异常!

我尝试过重置contenteditable属性来解决,虽然能阻止这个问题,但会导致虚拟键盘闪烁,体验很差,不是理想的解决方案。

// 编辑更新:我更新了代码,现在会捕获键码229,重置光标位置,并把输入内容设为&nbsp;

我的代码如下:

JavaScript代码:

let editableSpan = document.querySelector('#inp');

editableSpan.onkeydown = function(e){
    console.log('key pressed', e.which, e.key);
    if(e.key === 'Backspace' || e.key === 'Process'){
    var keyEls = document.querySelectorAll('#out .kbd');
    keyEls.length > 0 && keyEls[keyEls.length - 1].remove();
  }else if(e.key.length === 1){
    var keyEl = document.createElement('span');
    keyEl.classList.add('kbd');
    keyEl.textContent = e.key;
    document.querySelector('#out').append(keyEl);
  }
  e.preventDefault();
}

editableSpan.onkeyup = function(e){
  var letterInp = document.querySelector('#inp');
  var selection = window.getSelection();
  var range     = document.createRange();
  letterInp.innerHTML = '&nbsp;';
  range.setStart(letterInp, letterInp.childNodes.length);
  range.collapse(true);
  selection.removeAllRanges();
  selection.addRange(range);
}

CSS代码:

#inp {
  background-color: goldenrod;
  border: solid 3px black;
}
.kbd {
  display:inline-block;
  background-color:darkgrey;
  font-size: 2em;
  padding: .5em;
  margin-right: .3em;
  margin-top: .3em;
  border-radius:.3em;
  font-style:monospace;
}

HTML代码:

<span id="out"></span>
<span class="kbd" id="inp" contenteditable="true">&nbsp;</span>

备注:内容来源于stack exchange,提问作者Maze

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 08:35:30