使用Javascript 模擬鍵盤輸入


[代碼] 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');
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM