通過鍵盤方向鍵或電視遙控器控制焦點移動
阿新 • • 發佈:2019-01-02
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>通過鍵盤方向鍵或電視遙控器控制焦點移動</title> <style> div { width: 20%; height: 200px; background-color: red; border-radius: 12px; float: left; margin-left: 12px; margin-top: 12px; border: 2px solid black; } .active_li div { border: 2px solid blue; box-shadow: 0px 0px 1px #000; } ul { margin-left: 10%; width: 80%; } li { list-style: none; } </style> </head> <body> <ul> <li id="li_1_1" class="active_li"> <div></div> </li> <li id="li_1_2"> <div></div> </li> <li id="li_1_3"> <div></div> </li> <li id="li_1_4"> <div></div> </li> <li id="li_2_1"> <div></div> </li> <li id="li_2_2"> <div></div> </li> <li id="li_2_3"> <div></div> </li> </ul> </body> <script src="js/jquery-2.1.4.js"></script> <script> //使用jQuery監聽當前的按鍵值 $(document).on('keydown', function(e) { var actId = $(".active_li").attr("id"); var tempId = ""; switch (e.which) { case 37: //keyCode left if ($("#" + actId).prev().length > 0) { $("#" + actId).prev().addClass("active_li"); $("#" + actId).removeClass("active_li"); } break; case 38: // key code up tempId = actId.split("_")[0] + "_" + (parseInt(actId.split("_")[1]) - 1) + "_" + actId.split("_")[2]; if ($("#" + tempId).length > 0) { $("#" + tempId).addClass("active_li"); $("#" + actId).removeClass("active_li"); } break; case 39: //keycode right if ($("#" + actId).next().length > 0) { $("#" + actId).next().addClass("active_li"); $("#" + actId).removeClass("active_li"); } break; case 40: //keycode down tempId = actId.split("_")[0] + "_" + (parseInt(actId.split("_")[1]) + 1) + "_" + actId.split("_")[2]; if ($("#" + tempId).length > 0) { $("#" + tempId).addClass("active_li"); $("#" + actId).removeClass("active_li"); } break; } }); </script> </html>