JS中使用onkeydown事件来实现键盘效果

首先我们需要弄清楚

str="a";

code = str.charCodeAt(); //将字符转为对应的ASCII码 

str2 = String.fromCharCode(code);//将ASCII码转为对应的字符



<style type="text/css">
	li{cursor: pointer; list-style-type: none; border: 1px solid #F00;width: 80px;float: left; text-align: center; height: 30px; line-height: 30px;}
	.activeButton{background-color: #0F0}
</style>
<script type="text/javascript" src="./js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
	$(function(){
		var allKey=['~','!','@','#','$','%','^','&','*','(',')','-','+','Q','W','E','R','T','Y','u','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M'];
		var strHtml='';
		var code;
		for (var i = 0; i < allKey.length; i++) {
			code = allKey[i].charCodeAt(); //将字符转为对应的ASCII码
			strHtml+='<li class="keyButton" id="key'+code+'">'+allKey[i]+'</li>'
		};
		$("#keyBox").html(strHtml);

		$(window).keydown(function(event){
			var id="#key"+event.keyCode;
			$('.keyButton').removeClass('activeButton').filter(id).addClass('activeButton');
		});
		
	});
</script>
<div style="width:1000px; margin:0 auto; ">
	<ul id="keyBox">
	</ul>
</div>

你在键盘上相应的键,相应的键会变绿色。
JS中使用onkeydown事件来实现键盘效果_第1张图片

你可能感兴趣的:(JS中使用onkeydown事件来实现键盘效果)