[代碼] MSIE本地方法實現 - 不跨平台,不推薦使用
/** * 執行鍵盤上的按鍵或者字符串 * @param {String} character 要執行的鍵盤按鍵字符 */ function simulateKeyPress(character){ var wsh=new ActiveXObject("WScript.Shell"); wsh.SendKeys((character || '')); } window.onload = function(){ simulateKeyPress('{F11}'); }
[代碼] 利用jQuery類庫實現 - 跨平台,推薦使用
// jQuery插件。一個jQuery對象,而不是直接調用。 jQuery.fn.simulateKeyPress = function(character) { // 內部調用jQuery.event.trigger // 參數有 (Event, data, elem). 最后一個參數是非常重要的的! jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) }); }; //頁面調用 jQuery(document).ready( function($) { // 綁定事件處理程序 $( 'body' ).keypress( function(e) { alert( String.fromCharCode( e.which ) ); console.log(e); }); // 模擬按鍵了 x $( 'body' ).simulateKeyPress('x'); });