如何在输入上创建两个按钮,如Tab(下一个焦点)按键和Shift+Tab(上一个焦点)

How to create two button acts like Tab(next focus) keypress and Shift+Tab(previous focus) on inputs

本文关键字:焦点 Tab 下一个 上一个 Shift+Tab 两个 输入 创建 按钮      更新时间:2023-09-26

在网上搜索了2个小时后找不到我想要的东西。

我的问题是:我如何创建一个按钮,它的行为像"Tab键"answers"Shift + Tab键"它聚焦下一个输入文本或以前和第一次按将聚焦第一次输入。

像这样:

<div class="inputs">
    <input type="text" tabindex="1"/>
    <input type="text" tabindex="2" />
    <input type="text" tabindex="3" />
    <input type="text" tabindex="4" />
    <button>Tab(Go next input to Focus)</button>
    <button>Shift + Tab (fo Previous input to focus)</button>
</div>

很抱歉,我的问题和英语呈现得不好

如果您先将具有focusinput存储到var中,那么它真的很简单:

现场演示

var $curr;
$('.inputs input').on('focus',function(){
  $curr = $(this);
});
$('.prevTab, .nextTab').on('click', function( e ){
  $curr[ $(this).hasClass("nextTab") ? "next" : "prev" ]('input').focus();
});

更复杂的那行

$curr.prev('input').focus();$curr.next('input').focus();取决于使用简单的三元运算符逻辑单击哪个按钮:

if .nextTab is clicked ["next"] will be used
if .prevTab is clicked ["prev"] will be used

考虑到符号

$curr["next"]() is the same as $curr.next() method
$curr["prev"]() is the same as $curr.prev() method

只是用括号代替dot符号。

我们只是确保prevnext元素实际上是input使用:

 ('input').focus(); // and set the focus to it!