canrun
View Code
1 <html> 2 <head> 3 <title>jQuery Move Left Right By Keyboard</title> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <meta http-equiv="Content-Language" content="zh-CN" /> 6 <script type="text/javascript" src="https://files.cnblogs.com/Zjmainstay/jquery-1.6.2.min.js"></script> 7 </head> 8 <body> 9 <style> 10 li{ 11 border:1px solid #ABC; 12 display:block; 13 100px; 14 height:50px; 15 float:left; 16 margin:10px; 17 text-align:center; 18 } 19 li.curr{ 20 margin-top: -2px; 21 } 22 </style> 23 <div id="tips">请移动键盘左右箭头控制选定当前li</div> 24 <ul> 25 <li class="curr">1</li> 26 <li>2</li> 27 <li>3</li> 28 <li>4</li> 29 <li>5</li> 30 <li>6</li> 31 <li>7</li> 32 <li>8</li> 33 </ul> 34 <script type="text/javascript"> 35 $(document).ready(function(){ 36 $(document).keydown(function(e){ 37 var code; 38 if(!e) var e=window.event; 39 if(e.keyCode) { 40 code=e.keyCode; 41 }else if(e.which){ 42 code = e.which; 43 } 44 45 if(code == 37){ 46 movePrev(); 47 }else if(code == 39){ 48 moveNext(); 49 } 50 }); 51 52 var movePrev = function(){ 53 var index = $("li.curr").prevAll().length; 54 if(index == 0) $("li").removeClass('curr').eq($("li").length-1).addClass('curr'); //可循环移动 55 // if(index == 0) return false; //不可循环移动 56 else $("li").removeClass('curr').eq(index-1).addClass('curr'); 57 } 58 59 var moveNext = function(){ 60 var index = $("li.curr").prevAll().length; 61 if(index == $("li").length-1) $("li").removeClass('curr').eq(0).addClass('curr'); //可循环移动 62 // if(index == $("li").length-1) return false; //不可循环移动 63 else $("li").removeClass('curr').eq(index+1).addClass('curr'); 64 } 65 }); 66 </script> 67 </body> 68 </html>
效果图展示:
图一:
图二:
文件下载:jQuery用键盘控制li左右选定