我试图在调度的事件对象上设置keyCode.
单击按钮时,会在文本框控件上引发事件以模拟keydown事件.事件成功引发,但keyCode为0.我需要将具有正确keyCode的事件对象发送到文本框.我一直在使用这里的代码.
如何在调度事件中设置keyCode值?
<html>
<head>
</head>
<body>
<input type="button" id="btn" value="Click"></input>
<input type="text" id="txt"></input>
<script>
document.getElementById('btn').addEventListener("click", btnClick);
document.getElementById('txt').addEventListener("keydown", txtKeydown);
function btnClick(e) {
var txt = document.getElementById('txt');
var dispatchKeyboardEvent = function(target, initKeyboradEvent_args) {
var e = document.createEvent("KeyboardEvents");
e.initKeyboardEvent.apply(e, Array.prototype.slice.call(arguments, 1));
e.keyCode = 83;
e.charCode = 0;
target.dispatchEvent(e);
};
var canceled = !dispatchKeyboardEvent(txt,
'keydown', true, true, // type, bubbles, cancelable
window, // window
's', // key
0, // location: 0=standard, 1=left, 2=right, 3=numpad, 4=mobile, 5=joystick
false, false, false); // Ctr, …
Run Code Online (Sandbox Code Playgroud) 以下代码适用于Chrome,Firefox,iPhone,甚至Android上的第三方浏览器.但是,在本机浏览器中运行时,我的瑞典语键盘上的特殊字符(例如Å,Ä和Ö)的键事件根本不会被触发.
该示例应该只允许用户一次输入一个字符.像魅力一样,除非我在安卓按键,如Å,Ä或Ö,我可以输入任意数量的字符.
对于任何想要试用它的人来说,这是一个jsFiddle:http://jsfiddle.net/x7H6f/.如果你没有像键盘上印刷的瑞典语那样的特殊键,那么像é(举行E)这样的字符应该是"技巧".
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Key Event test</title>
</head>
<body>
<input type="text" id="a" name="test" />
<script>
document.getElementById("a").onkeypress = function(e) {
e = e || window.event;
var k = e.keyCode || e.which;
this.value = String.fromCharCode(k);
return false;
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
不,keydown和keyup也不起作用.我错过了什么,或者这是一个错误?在PhoneGap中开发瑞典应用程序时非常烦人!
谢谢!
编辑:
正如庄园在他的回答中所说,input
可以使用该事件.下面是这表明了之间的差异的小提琴keypress
,input
和change
事件:http://jsfiddle.net/Qxd76/(使用http://jsfiddle.net/Qxd76/show查看在智能手机上的结果).
我一直试图让它工作,但我不知道发生了什么,我的代码:
$('#buscar-producto').on('keydown', function(e){
console.log('hello');
console.log(e.keyCode);
});
Run Code Online (Sandbox Code Playgroud)
电脑上可以用,手机不行。。
编辑: 我需要在按下某个键时获取 keyCode ......