使用JavaScript或jquery实现箭头键

Implementation of Arrow keys using JavaScript or jquery

本文关键字:实现 jquery JavaScript 使用      更新时间:2023-09-26

我有一个jsp页面,我想在页面中实现上下左右键功能。我有以下代码,但它访问只读文本框以及。我想跳过只读输入。请查看附件的snap。我有A B C D E F G H输入但是E和F是只读的。我的光标在c上,假设如果我按下键(代码=40),那么它应该通过跳过E和f而转到G。请点击此链接查看图片:

https://www.dropbox.com/s/ptm483avp8pm9sg/Untitled.png?dl=0

$(document).ready(function(){  
    $("input,textarea").keydown(function(e) {      
     if (e.keyCode==37 || e.keyCode==38 ) {
           $(":input,textarea,select")[$(":input,select").index(document.activeElement) - 1].focus();            
     }
     if (e.keyCode==39 || e.keyCode==40 ) {
           $(":input,textarea,select")[$(":input,select").index(document.activeElement) + 1 ].focus();           
     }
 }); 
});

您可以使用:not([readonly])选择器。例句:

$(document).ready(function(){
    $("input,textarea").keydown(function(e) {
     if (e.keyCode==37 || e.keyCode==38 ) {
       $(":input:not([readonly]),textarea,select")[$(":input:not([readonly]),select").index(document.activeElement) - 1].focus();
     }
     if (e.keyCode==39 || e.keyCode==40 ) {
       $(":input:not([readonly]),textarea,select")[$(":input:not([readonly]),select").index(document.activeElement) + 1 ].focus();
     }
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' value='A' />
<input type='text' value='B' />
<input type='text' value='C' />
<input type='text' value='D' />
<input type='text' value='E' readonly />
<input type='text' value='F' readonly />
<input type='text' value='G' />
<input type='text' value='H' />

修改你的jquery选择器以排除被禁用的元素

$(":input,select").not(":disabled").index(...