2010-06-18 37 views
2

我想要触发与按住具有焦点的元素上的tab键相同的效果。有没有办法做到这一点?我试图让焦点跳到下一个元素。HTML元素:我怎样才能模拟按下'tab'键

谢谢!

(jQuery是一个选项)

+0

http://stackoverflow.com/questions/1803338/simulate-the-tab-key-function-in-javascript – 2010-06-18 21:51:23

+0

的可能的复制DanC,你有没有发现该问题的解决方案?我有同样的任务。 Stephen P,这不是重复的,有些情况下很难找到应该关注的页面上的下一个活动元素。 – whitered 2010-12-22 09:19:28

+0

Stephen P,不,我没有找到答案。我重构了我的代码,以便它可以或多或少地完成这项工作,但我无法模拟按Tab键的效果。 – DanC 2010-12-22 13:59:48

回答

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> 
0

需要在一个前一阵子模仿的标签功能,现在我已经released it as a library使用

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

您可以see how it works in the demo

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