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

虚拟键盘重新聚焦输入元素时cursorPosition异常问题求助

虚拟键盘重新聚焦输入元素时cursorPosition异常问题求助

大家好,我正在开发一个虚拟键盘,普通单次输入的功能是正常的,但当用setInterval实现长按重复输入时,如果期间重新聚焦输入元素,光标位置就会乱跳。我怀疑是某个步骤的执行顺序出了问题,有没有大佬能帮我排查一下问题所在?

以下是我的完整代码:

const keyboard = document.querySelector(".keyboard");

const validInputEls = [HTMLInputElement, HTMLTextAreaElement];

// variables and flags
let lastFocusedInput, isTyping, typingInterval, typingTimeout;

// get key/value handle exceptions (currently with warnings and early returns)
function handleKeyboard(event) {
  const key = event.target.closest(".key");
  if (!key) return;

  if (!lastFocusedInput) {
    console.warn("Please first choose a target for your input!");
    return;
  }

  if (!isTyping) {
    // start typing in interval here
    isTyping = true;
    let char = key.dataset.value;
    char = char === "Space" ? "\xa0" : char; // doesn't print " "

    if (!char) {
      console.warn(`Currently no action associated with ${key.innerText}-key.`);
      return;
    }

    type(char);
    typingTimeout = setTimeout(() => {
      typingInterval = setInterval(() => type(char), 150);
    }, 500);
  }
}

function type(char) {
  const cursorPosition = lastFocusedInput.selectionStart;
  const text = lastFocusedInput.value;
  const newValue =
    text.substring(0, cursorPosition) + char + text.substring(cursorPosition);
  lastFocusedInput.value = newValue;
  const newCursorPosition = cursorPosition + 1;
  lastFocusedInput.setSelectionRange(newCursorPosition, newCursorPosition);
}

function stopTyping() {
  clearTimeout(typingTimeout); // Cancel the typing timeout
  clearInterval(typingInterval);
  isTyping = false;
}

// set focused if valid
document.addEventListener("focusin", (event) => {
  if (!validInputEls.includes(event.target.constructor)) return;
  lastFocusedInput = event.target;
});

keyboard.addEventListener("mousedown", handleKeyboard);
keyboard.addEventListener("mouseup", stopTyping);
keyboard.addEventListener("mouseleave", stopTyping);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 10:30:25