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

jQuery .keypress返回值在iOS上不显示的问题求助(数独表格场景)

解决iOS旧版本下数独输入框内容不显示的问题

我之前也碰到过类似的旧iOS WebKit兼容性坑,你的情况大概率是**keypress事件同步切换焦点打断了输入内容渲染**导致的。旧版本iOS(比如9.3.5)的Safari/Chrome内核在处理keypress事件时,如果同步执行焦点切换,会直接中断当前输入框的内容更新流程——因为焦点已经转移,浏览器会放弃渲染刚刚输入的字符;只有最后一个输入框因为没有下一个焦点可切换,所以内容能正常显示。

核心解决方案:异步执行焦点切换

把焦点跳转的逻辑放到setTimeout里,让浏览器先完成输入内容的渲染,再执行焦点切换。修改后的代码如下:

$('.box').keypress(function(event) {
    const $currentInput = $(this);
    const keyCode = event.which;

    // 处理Enter键:允许提交,不跳转焦点
    if (keyCode === 13) {
        return true;
    }

    // 处理1-9数字:允许输入,异步跳转焦点
    if (keyCode >= 49 && keyCode <= 57) {
        setTimeout(() => {
            if ($currentInput.parent().is('td:last-child')) {
                $currentInput.closest('tr').next().children().first().find('.box').focus();
            } else {
                $currentInput.parent().next().find('.box').focus();
            }
        }, 0);
        return true;
    }

    // 处理0键:不输入内容,异步跳转焦点
    if (keyCode === 48) {
        setTimeout(() => {
            if ($currentInput.parent().is('td:last-child')) {
                $currentInput.closest('tr').next().children().first().find('.box').focus();
            } else {
                $currentInput.parent().next().find('.box').focus();
            }
        }, 0);
        return false;
    }

    // 其他无效按键:阻止输入
    return false;
});

额外优化建议

  1. 替换event.which为兼容属性:event.which已被规范废弃,建议兼容event.keyCode和event.which(写成const keyCode = event.keyCode || event.which;),旧iOS环境下这个兼容写法更稳妥。
  2. 检查输入框类型:如果你的输入框是type="number",iOS的数字键盘可能会触发特殊的事件行为,建议改成type="text",通过代码限制输入范围,避免类型带来的兼容性问题。
  3. 尝试完整版jQuery:虽然jQuery 3.2.1 slim版保留了事件处理模块,但旧版本slim可能缺失部分针对旧浏览器的补丁,如果异步方案无效,可以换成完整版jQuery测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:29:49