2010-06-18 115 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(); 
} 
相關問題