当前位置: 代码迷 >> JavaScript >> javascript怎么模拟键盘按上
  详细解决方案

javascript怎么模拟键盘按上

热度:470   发布时间:2012-09-13 09:51:52.0
javascript如何模拟键盘按下
需要写一个js方法:escKeyPress()。这个方法用于模拟按下键盘上的ESC键,我现在有一个模拟鼠标左键单击的js方法,
JScript code

function doClick(linkId){  
    
    var fireOnThis = document.getElementById(linkId);
    
      if (document.createEvent)
      {
        var evObj = document.createEvent('MouseEvents');
        evObj.initEvent( 'click', true, false );
        fireOnThis.dispatchEvent(evObj);
      }
      else if (document.createEventObject)
      {
           fireOnThis.fireEvent('onclick');
      }
}


是从网上找的,但是本人太菜,搜了半天也弄不到模拟键盘点击的js方法,请求大虾帮忙!!

------解决方案--------------------
Hi,
我写了个例子,在IE6和Firefox3.5中已经测试过. 你要是想支持其他浏览器需要查相应的文档。 

用法:
创建一个新HTML文件,copy下面的内容进去就可以了

--------------------------------------------

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Simulate Event</title>
<script type="text/javascript">
function simulateKeyEvent(target, 
keyCode)
{
  
if (!target){
alert("Target is not exist");
}

var customEvent = null;
var a = typeof document.createEvent;

if(typeof document.createEvent == "function")
{
try {

//firefox
customEvent = document.createEvent("KeyEvents");
customEvent.initKeyEvent("keypress", true, true,window, false,
false,false, false, keyCode, keyCode);

} catch (ex){

document.write("Shit happends. This example is only demonstrating event simulation in firefox and IE.");
}
target.dispatchEvent(customEvent);

} else if (document.createEventObject){ //IE

customEvent = document.createEventObject();

customEvent.bubbles = true;
customEvent.cancelable = true;
customEvent.view = window;
customEvent.ctrlKey = false;
customEvent.altKey = false;
customEvent.shiftKey = false;
customEvent.metaKey = false;
customEvent.keyCode = keyCode;

target.fireEvent("onkeypress", customEvent);

} else {
document.write("This example is only demonstrating event simulation in firefox and IE.");
}
}


</script>
</head>
<body>
<input id="testinput" type="button" value="kick you"/>
</body>
<script type="text/javascript">



var target =document.getElementById("testinput");
target.onkeypress = function(event){
var event = (event)?event:window.event;
if(event.keyCode == 27){
alert('"ESC" pressed');
}
};
simulateKeyEvent(target,27);
</script>

</html>
  相关解决方案