我正在尝试使用javascript按下我页面上的输入键。
需要像以下一行代码一样:
javascript:oninputmyInput.pressKeynum1();
可以这样做吗?
答案 0 :(得分:1)
根据评论发布,即使jquery
也未标记
// dummy event listener
$("input").keydown(function() { return true; });
var keyEvent = jQuery.Event("keydown");
keyEvent.keyCode = 13;
$("input").trigger(keyEvent);
用此手动触发keydown
事件,这适用于enter
事件
答案 1 :(得分:1)
如果你可以使用jQuery Workig JsFiddle:
// jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function(character) {
// Internally calls jQuery.event.trigger
// with arguments (Event, data, elem). That last arguments is very important!
jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};
jQuery(document).ready( function($) {
// Bind event handler
$( 'body' ).keypress( function(e) {
alert( String.fromCharCode( e.which ) );
console.log(e);
});
// Simulate the key press
$( 'body' ).simulateKeyPress('x');
});
适用于webkit和gecko的非jquery版本:
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keydown", // event type : keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // viewArg: should be window
false, // ctrlKeyArg
false, // altKeyArg
false, // shiftKeyArg
false, // metaKeyArg
40, // keyCodeArg : unsigned long the virtual key code, else 0
0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);