1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title></title> 5 <script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script> 6 <style type="text/css"> 7 *{margin:0px;padding:0px;} 8 body{font-size:12px;} 9 10 .box{margin:10px;padding:10px;} 11 .box h3{margin:10px 0px;border-bottom:1px solid red;padding-bottom:10px;} 12 .box p{line-height:20px;} 13 14 #databox{margin:10px auto;padding:10px;width:470px;border:5px solid pink;display:table;} 15 #databox img{float:left;border:5px solid #11cc99;width:130px;height:160px;margin:8px;} 16 #databox img.selected{border:5px solid red;} 17 18 </style> 19 <script type="text/javascript"> 20 $(function(){ 21 22 $("body").keydown(function(event){ 23 var num = event.which; 24 25 switch(num){ 26 case 38: 27 var postion =parseInt($(".selected").attr("picid")); 28 $(".selected").removeAttr("class"); 29 30 if(postion < 4){ 31 var k = postion + 6; 32 }else{ 33 var k = postion - 3; 34 } 35 $("img[picid="+k+"]").attr("class","selected"); 36 break; 37 case 40: 38 var postion =parseInt($(".selected").attr("picid")); 39 $(".selected").removeAttr("class"); 40 if(postion > 6){ 41 var k = postion - 6; 42 }else{ 43 var k = postion + 3; 44 } 45 $("img[picid ="+k+"]").attr("class","selected"); 46 break; 47 case 37: 48 var postion =parseInt($(".selected").attr("picid")); 49 $(".selected").removeAttr("class"); 50 if(postion % 3 == 1){ 51 var k = postion +2; 52 }else{ 53 var k = postion -1; 54 } 55 $("img[picid ="+k+"]").attr("class","selected"); 56 break; 57 case 39: 58 var postion =parseInt($(".selected").attr("picid")); 59 $(".selected").removeAttr("class"); 60 if(postion % 3 == 0){ 61 var k = postion-2; 62 }else{ 63 var k = postion +1; 64 } 65 $("img[picid ="+k+"]").attr("class","selected"); 66 break; 67 case 13: 68 //查找领导人的名字 69 var name = $(".selected").attr("title"); 70 alert(name); 71 break; 72 default: 73 alert("您输入的按键不对!"); 74 break; 75 } 76 77 }); 78 79 }); 80 81 </script> 82 83 84 </head> 85 <body> 86 <div class="box"> 87 <h3>试题要求</h3> 88 <p> 89 1.请从下面的国家领导人中选择你最喜欢的一个。<br /> 90 2.通过上下左右四个按键进行选取。<br /> 91 3.选择完毕后,按下enter键,以对话框的形式将领导人的名字弹出来。<br /> 92 4.提示:上下左右四个键的值分别为:38、40、37、39;回车键的值为:13;获取建值可以通过事件对象的which属性获取:event.which。 93 </p> 94 </div> 95 96 <div id="databox"> 97 98 <img picid="1" src="Pictures/胡**.jpg" title="胡**" /> 99 <img picid="2" src="Pictures/习**.jpg" title="习**" class="selected" /> 100 <img picid="3" src="Pictures/贾**.jpg" title="贾***" /> 101 <img picid="4" src="Pictures/江**.jpg" title="江**" /> 102 <img picid="5" src="Pictures/李**.jpg" title="李**" /> 103 <img picid="6" src="Pictures/毛**.jpg" title="毛**" /> 104 <img picid="7" src="Pictures/王**.jpg" title="王**" /> 105 <img picid="8" src="Pictures/温**.jpg" title="温**" /> 106 <img picid="9" src="Pictures/吴**.jpg" title="吴**" /> 107 108 </div> 109 </body> 110 </html>
原文:http://www.cnblogs.com/huyang1988/p/5040537.html