【问题标题】:Change focus on value inserted更改对插入值的关注
【发布时间】:2017-02-03 15:22:15
【问题描述】:

我的问题:插入字符后,我必须专注于下一个文本输入。此输入只能包含一个字符,特别是一个数字。

我的解决方案(伪代码):

onKeyUp="nextInput.focus()"

...在桌面上运行良好,但在移动设备上,有时值是在移动到下一个字段(在错误的单元格中)之后写入的。

我的第二个解决方案:

onChange="nextInput.focus()"

不起作用,因为只有当 HTML 元素失去焦点时才会调用 onchange 事件。

【问题讨论】:

    标签: javascript jquery events onchange onkeyup


    【解决方案1】:

    它似乎在我的 safari iphone 中工作:

    $("#first").on('keyup', function(e){ 
      if(isCharacterKeyPress(e)){
        $("#second").focus();
          console.log(e);
      }
    });
    
    function isCharacterKeyPress(evt) {
        if (typeof evt.which == "undefined") {
            // This is IE, which only fires keypress events for printable keys
            return true;
        } else if (typeof evt.which == "number" && evt.which > 0) {
            // In other browsers except old versions of WebKit, evt.which is
            // only greater than zero if the keypress is a printable key.
            // We need to filter out backspace and ctrl/alt/meta key combinations
            return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
        }
        return false;
    }
    

    请检查:https://jsfiddle.net/9u9hb839/4/

    已编辑:

    为了防止检测到其他按键而不是字符,我更新了我的代码:

    var keypressed = false;
    
    $("#first").on('keyup', function(e){
        console.log('keyup');
      if(keypressed){
        $("#second").focus();
      }
      keypressed = false;
    });
    
    $("#first").on('keypress', function(e){
        console.log('keypress');
        keypressed = isCharacterKeyPress(e);
    });
    
    function isCharacterKeyPress(evt) {
        if (typeof evt.which == "undefined") {
            // This is IE, which only fires keypress events for printable keys
            return true;
        } else if (typeof evt.which == "number" && evt.which > 0) {
            // In other browsers except old versions of WebKit, evt.which is
            // only greater than zero if the keypress is a printable key.
            // We need to filter out backspace and ctrl/alt/meta key combinations
            return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
        }
        return false;
    }
    

    试试这个:https://jsfiddle.net/9u9hb839/9/

    在移动设备(safari、chrome)和桌面设备(chrome、firefox)中测试

    【讨论】:

      【解决方案2】:

      我发现的唯一解决方案,也适用于移动环境:

       function moveFocus(evt, id) {  
             setTimeout(function () {
                  document.getElementById(id).focus();
                  document.getElementById(id).select();
             }, 100); 
       }
      

      【讨论】:

        猜你喜欢
        • 2013-08-23
        • 1970-01-01
        • 1970-01-01
        • 2019-01-07
        • 2014-09-17
        • 2013-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多