标签:javaweb
学完了JavaScript之后,自己突发奇想,想写一个模拟键盘的小程序。代码如下:
<!doctype html> <html lang="en"> <!-- 需求:通过键盘点击,结合键盘事件来模拟按下了哪个键。 onkeydown onkeyup 思路: 1.在onload事件中创建键盘视图 2.定义一个输入框来接收和触发键盘事件 3.同时返回按下的那个键的keyCode值 --> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>模拟键盘</title> <style type="text/css"> /*键盘外边框格式*/ #keycontainer{ border:3px solid red; padding:50px 50px; } /*每个按键的格式*/ span{ border:1px solid red; background:black; width:50px; color:white; font-size:1cm; display:inline-block; padding:1px; } /*输入框的格式*/ #input{ border:1px solid red; } </style> </head> <body onload="initView();"> <marquee behavior="alternate"><font size="6" color="BlueViolet" ><b>键盘测试程序 作者:陈章 黑马程序员【Android70期】</b></font></marquee> <div id="keycontainer"></div> <hr/> 请在下面的文本框中按下任意一个键<br/> <input type="text" id="input" onkeydown="keydown(event);" onkeyup="keyup(event);"/> </body> <script type="text/javascript"> //工具函数 function outln(str) { document.writeln(str); } function out(str) { document.write(str); } function byID(id) { return document.getElementById(id); } var colorBefore; function byName(name) { return document.getElementsByName(name)[0]; } function keydown(e) { //遍历键盘的各个键,看哪个的值与键盘按下的值相匹配。 var keys = document.getElementsByTagName("span"); for(var i = 0; i < keys.length; i++) { var each = keys[i]; if(each.innerHTML == String.fromCharCode(e.keyCode)) { colorBefore = each.style.backgroundColor; each.style.backgroundColor = "blue"; return; } } } function keyup(e){ //遍历键盘的各个键,看哪个的值与键盘按下的值相匹配。 var keys = document.getElementsByTagName("span"); for(var i = 0; i < keys.length; i++) { var each = keys[i]; if(each.innerHTML == String.fromCharCode(e.keyCode)) { each.style.backgroundColor = colorBefore; byID("input").value=String.fromCharCode(e.keyCode) + " keyCode值:" + e.keyCode; return; } //如果按下的键没有的话 byID("input").value= "? keyCode值:" + e.keyCode; } } // <!--初始化键盘视图--> function initView() { var main = byID("keycontainer"); var s = ""; s += "<span >Q</span > "; s += "<span >W</span> "; s += "<span >E</span> "; s += "<span >R</span> "; s += "<span >T</span> "; s += "<span >Y</span> "; s += "<span >U</span> "; s += "<span >I</span> "; s += "<span >O</span> "; s += "<span >P</span> <br/><br/>"; s += " <span >A</span> "; s += "<span >S</span> "; s += "<span >D</span> "; s += "<span >F</span> "; s += "<span >G</span> "; s += "<span >H</span> "; s += "<span >J</span> "; s += "<span >K</span> "; s += "<span >L</span> <br/><br/>"; s += " <span >Z</span> "; s += "<span >X</span> "; s += "<span >C</span> "; s += "<span >V</span> "; s += "<span >B</span> "; s += "<span >N</span> "; s += "<span >M</span> "; main.innerHTML = s; } </script> </html>
程序在桔子浏览器中运行之后效果如下:
当按下A-Z字母时,会显示字母和对应的keyCode值;其它的键会显示?和keyCode值。
本文出自 “行意天下” 博客,请务必保留此出处http://4259297.blog.51cto.com/4249297/1666096
标签:javaweb
原文地址:http://4259297.blog.51cto.com/4249297/1666096