gpt4 book ai didi

javascript - 仅当按下 Tab 按钮时在两个文本区域之间切换

转载 作者:行者123 更新时间:2023-11-29 09:56:40 26 4
gpt4 key购买 nike

通常,当用户访问网页并按下键盘上的 TAB 键时,选择从页面的开头开始从一个元素移动到另一个元素。

我正在寻找一种解决方案,通过按键盘上的 TAB 按钮在两个特定文本区域之间切换,并在加载网页时将初始焦点放在第一个文本区域上?对于此 TAB 键按下事件,必须忽略页面上的所有其他元素。

我怎样才能做到这一点?

感谢您的帮助!

=更新=

我已经设法让它在 Firefox 12.0 下工作。 IE 和 Chrome 不能正常工作。假设文本区域 ID 是#ICCID 和#MSISDN,Jquery 看起来像这样:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$("#ICCID").focus();
});

var $inp = $('.cls');

$inp.bind('keydown', function(e) {
var key = e.which;
if (key == 9) {

e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(".cls:eq(" + nxtIdx + ")").focus();

//Simulate Enter after TAB
var textInput = $("#MSISDN").val();
var lines = textInput .split(/\r|\r\n|\n/);
if (lines > 1) {

$("#MSISDN").on("keypress", function(e) {
if (e.keyCode == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\n");
}, 1);
}
});
}



}
if (key == 9) {

e.preventDefault();
var nxtIdx = $inp.index(this) - 1;
$(".cls:eq(" + nxtIdx + ")").focus();

//Simulate Enter after TAB
$("#ICCID").on("keypress", function(e) {
if (e.keyCode == 9) {
var input = $(this);
var inputVal = input.val();
setTimeout(function() {
input.val(inputVal.substring(0,inputVal.length) + "\n");
}, 1);
}
});


}
});
});
</script>

最佳答案

使用 jQuery 捕获 keydown Action ,确定哪个 textarea 具有焦点,然后使用 focus() 方法将焦点设置到另一个 textarea。

假设您的文本区域有 id="textarea1"和 id="textarea2"。首先,您可以在页面加载时将焦点设置到第一个文本区域:$('#textarea1').focus();

$("body").keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
switch(code)
{
case 9:
if($("#textarea1").focus()){
//First one has focus, change to second one
$("#textarea2").focus();
}
else if($("#textarea2").focus()) {
//Second one has focus, change to first one
$("#textarea1").focus();
}

}
});

关于javascript - 仅当按下 Tab 按钮时在两个文本区域之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10515830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com