javascript keyup、keydown 和 keypress 事件在移动设备上不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47478453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:24:14  来源:igfitidea点击:

keyup, keydown and keypress events not working on mobile

javascriptjquery

提问by Aarón Gutiérrez

I have been trying to get this to work but I don't know what's going on, the code I have:

我一直试图让它工作,但我不知道发生了什么,我的代码:

$('#buscar-producto').on('keydown', function(e){
    console.log('hello');
    console.log(e.keyCode);
});

It works on computers, but not on mobile..

电脑上可以用,手机不行

EDIT:I need to get the keyCode when a key is pressed...

编辑:我需要在按下某个键时获取 keyCode...

回答by Roko C. Buljan

keydownshouldwork, but you could use the inputevent which seems to have undesired effects on Android mobile...
To get the codeof the pressed key use the jQuery's normalized Event.which

keydown应该可以工作,但是您可以使用input似乎对 Android 手机产生不良影响的事件...
要获取按键的代码,请使用 jQuery 的规范化Event.which

Android Chrometested:

安卓 Chrome测试:

Using inputEvent (e.whichgives always 0so it seems like a bug on android devices)

使用input事件(e.which总是给出,0所以它似乎是 android 设备上的一个错误)

jQuery(function($) { // DOM ready and $ alias secured

  $('#buscar-producto').on('input', function(e){
    var key = e.which || this.value.substr(-1).charCodeAt(0);
    alert( key )
  });

});
<input type="text" id="buscar-producto" placeholder="Buscar...">

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Using keydown(works as expected)

使用keydown(按预期工作)

jQuery(function($) { // DOM ready and $ alias secured

  $('#buscar-producto').on('keydown', function(e){
    alert( e.which );
  });

});
<input type="text" id="buscar-producto" placeholder="Buscar...">

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>