【问题标题】:HTML elements: How can I simulate pressing the 'tab' keyHTML 元素:如何模拟按下“tab”键
【发布时间】:2012-08-14 05:33:22
【问题描述】:

我想触发与在具有焦点的元素上按 Tab 键时相同的效果。有没有办法做到这一点?我正在尝试让焦点跳转到下一个元素。

谢谢!

(jQuery 是一个选项)

【问题讨论】:

  • DanC,您找到解决问题的方法了吗?我有同样的任务。 Stephen P,这不是重复的,在某些情况下,很难在页面上找到下一个应该关注的活动元素。
  • Stephen P,不,我没有找到答案。我重组了我的代码,以便它或多或少地完成这项工作,但我无法模拟按 Tab 键的效果。
  • @whitered:添加了一个可能对您有所帮助的新答案。

标签: javascript jquery tabs focus elements


【解决方案1】:

类似这样的东西(使用 jQuery):

    <!DOCTYPE html>

    <html lang="en">

        <head>

            <title>LOL Focus!</title>

            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>

        </head>

        <form>
          <input class="focusable" type="text" value="lol"/>
          <input class="focusable" type="text" value="lol" />
          <input class="focusable" type="text" value="lol" />
          <input class="focusable" type="text" value="lol" />
          <input class="focusable" type="text" value="lol" />
          <input class="focusable" type="text" value="lol" />                 
        </form> 

        <input type="button" id="trigger_button" value="lol" />

        <script type="text/javascript">
        $(function() {

          var focusable = $('.focusable'),
              last_element_index = focusable.length - 1,
              current_index;

          focusable.each(function(i) {
            $(this).click(function() {
              current_index = i;
            })
          });

           $('#trigger_button').click(function() {
             current_index = (should_reset_current_index()) ? 0 : current_index + 1;
             focusable[current_index].focus();
           });

           function should_reset_current_index() {
             return (typeof(current_index) === 'undefined') || (current_index == last_element_index)
           }

        });
      </script>

    </html>

【讨论】:

    【解决方案2】:

    不久前需要模拟选项卡功能,现在我有使用released it as a library

    EmulateTab:一个 jQuery 插件,用于模拟页面上元素之间的制表符。

    你可以see how it works in the demo

    if (myTextHasBeenFilledWithText) {
      // Tab to the next input after #my-text-input
      $("#my-text-input").emulateTab();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-10
      • 2018-08-14
      • 2011-04-26
      • 2021-12-26
      • 2012-03-02
      • 2019-10-31
      • 1970-01-01
      • 2012-02-19
      相关资源
      最近更新 更多