【问题标题】:Enter key press behaves like a Tab in JavascriptEnter 按键的行为类似于 Javascript 中的 Tab
【发布时间】:2010-11-03 20:00:29
【问题描述】:

我正在寻找创建一个表单,在该表单中按下回车键会导致焦点转到页面上的“下一个”表单元素。我一直在网上找到的解决方案是……

 <body onkeydown="if(event.keyCode==13){event.keyCode=9; return event.keyCode}">

不幸的是,这似乎只适用于 IE。所以这个问题的真正实质是是否有人知道适用于 FF 和 Chrome 的解决方案?此外,我宁愿不必将 onkeydown 事件添加到表单元素本身,但如果这是唯一的方法,那就必须这样做。

这个问题类似于question 905222,但在我看来应该是它自己的问题。

编辑:另外,我看到人们提出这种风格不好的问题,因为它与用户习惯的表单行为不同。我同意!这是一个客户请求:(

【问题讨论】:

    标签: javascript html cross-browser dom-events


    【解决方案1】:
    function return2tab (div)
    {
        document.addEventListener('keydown', function (ev) {
            if (ev.key === "Enter" && ev.target.nodeName === 'INPUT') {
    
                var focusableElementsString = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable]';
    
                let ol= div.querySelectorAll(focusableElementsString);
    
                for (let i=0; i<ol.length; i++) {
                    if (ol[i] === ev.target) {
                        let o= i<ol.length-1? ol[i+1]: o[0];
                        o.focus(); break;
                    }
                }
                ev.preventDefault();
            }
        });
    }
    

    【讨论】:

      【解决方案2】:

      这对我有用:

      $(document).on('keydown', ':tabbable', function(e) {
      
          if (e.key === "Enter") {
              e.preventDefault();
      
              var $canfocus = $(':tabbable:visible');
              var index = $canfocus.index(document.activeElement) + 1;
      
              if (index >= $canfocus.length) index = 0;
              $canfocus.eq(index).focus();
          }
      
      });
      

      【讨论】:

      • 这个doesn't seem to be working。小提琴链接已失效(并且已被删除)。
      • 这将需要 jquery-ui 用于 tabbable 选择器
      【解决方案3】:

      我使用了 Andrew 建议的逻辑,非常有效。这是我的版本:

      $('body').on('keydown', 'input, select', function(e) {
          if (e.key === "Enter") {
              var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
              focusable = form.find('input,a,select,button,textarea').filter(':visible');
              next = focusable.eq(focusable.index(this)+1);
              if (next.length) {
                  next.focus();
              } else {
                  form.submit();
              }
              return false;
          }
      });
      

      KeyboardEvent 的键码(即:e.keycode)折旧通知:-https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

      【讨论】:

      • 我建议从第一行的选择器中删除textarea。在文本区域中,您希望能够使用回车键开始新行。
      • 我建议忽略带有readonlydisabled的字段:filter(':visible:not([readonly]):enabled')
      • 这里为什么使用“self”变量?
      • 我知道这是一个非常古老的线程,但是使用这段代码,我们如何允许 的默认行为?如何允许使用 Enter 键单击按钮?
      【解决方案4】:

      用JavaScript的焦点函数解决这个问题的最简单方法如下:

      你可以在@home复制试试!

      <!DOCTYPE html>
      <html lang="en" dir="ltr">
        <head>
          <meta charset="utf-8">
          <title></title>
        </head>
        <body>
      
          <input id="input1" type="text" onkeypress="pressEnter()" />
          <input id="input2" type="text" onkeypress="pressEnter2()" />
          <input id="input3" type="text"/>
      
          <script type="text/javascript">
          function pressEnter() {
            // Key Code for ENTER = 13
            if ((event.keyCode == 13)) {
              document.getElementById("input2").focus({preventScroll:false});
            }
          }
          function pressEnter2() {
            if ((event.keyCode == 13)) {
              document.getElementById("input3").focus({preventScroll:false});
            }
          }
          </script>
      
        </body>
      </html>
      

      【讨论】:

        【解决方案5】:
        $("#form input , select , textarea").keypress(function(e){
            if(e.keyCode == 13){
                var enter_position = $(this).index();
                $("#form input , select , textarea").eq(enter_position+1).focus();
            }
        });
        

        【讨论】:

        • 能否请您提供代码的小解释以使答案更容易理解?
        • 首先你需要选择表单中的所有输入字段,然后你需要在每个输入字段中绑定keypress事件,然后你需要检查是否输入keypress以及何时按下输入键字段,您需要获取此输入字段的索引并将增量添加到它的索引以查找下一个输入字段,当您找到下一个输入字段时,您需要关注它......!
        【解决方案6】:

        这里的许多答案使用已弃用的 e.keyCodee.which

        您应该使用e.key === 'Enter'

        文档:https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

        • 很抱歉,我现在无法测试这些 sn-ps。测试后会回来。

        使用 HTML:

        <body onkeypress="if(event.key==='Enter' && event.target.form){focusNextElement(event); return false;}">
        

        使用 jQuery:

        $(window).on('keypress', function (ev)
        {
            if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev)
        }
        

        还有香草 JS:

        document.addEventListener('keypress', function (ev) {
            if (ev.key === "Enter" && ev.currentTarget.form) focusNextElement(ev);
        });
        

        您可以从这里获取focusNextElement() 函数: https://stackoverflow.com/a/35173443/3356679

        【讨论】:

          【解决方案7】:

          这就是我想出的。

          form.addEventListener("submit", (e) => { //On Submit
           let key = e.charCode || e.keyCode || 0 //get the key code
           if (key = 13) { //If enter key
              e.preventDefault()
              const inputs = Array.from(document.querySelectorAll("form input")) //Get array of inputs
              let nextInput = inputs[inputs.indexOf(document.activeElement) + 1] //get index of input after the current input
              nextInput.focus() //focus new input
          }
          }
          

          【讨论】:

          • 欢迎来到 Stack Overflow。目前,这个问题还有19个其他答案。如果您希望为自己的作品赢得投票,请考虑解释为什么它比其他作品更好。
          【解决方案8】:

          我遇到了类似的问题,我想在小键盘上按 + 以跳到下一个字段。现在我发布了一个我认为会对你有所帮助的库。

          PlusAsTab:一个 jQuery 插件,使用数字键盘加键作为 Tab 键等效项。

          由于您想要 enter/ 代替,您可以设置选项。找出您要与jQuery event.which demo 一起使用的密钥。

          JoelPurra.PlusAsTab.setOptions({
            // Use enter instead of plus
            // Number 13 found through demo at
            // https://api.jquery.com/event.which/
            key: 13
          });
          
          // Matches all inputs with name "a[]" (needs some character escaping)
          $('input[name=a\\[\\]]').plusAsTab();
          

          您可以在PlusAsTab enter as tab demo 中亲自试用。

          【讨论】:

          • 这很有趣。但是我有一个问题:如果在页面加载后添加了更多的 UI 元素(比如使用带有可观察数组的敲除绑定时)会发生什么?需要做什么才能让新添加的控件也将 Enter 作为 Tab 处理?谢谢
          • @bzamfir:如果它在包含data-plus-as-tab="true" 的元素内,则无需执行任何操作,否则可以运行$("#new-input").plusAsTab()。查看Dynamic elements 和此Improving user experience in HTML forms demo 中的示例实现。
          【解决方案9】:

          试试这个...

          $(document).ready(function () {
              $.fn.enterkeytab = function () {
                  $(this).on('keydown', 'input,select,text,button', function (e) {
                      var self = $(this)
                        , form = self.parents('form:eq(0)')
                        , focusable
                        , next
                      ;
                      if (e.keyCode == 13) {
                          focusable = form.find('input,a,select').filter(':visible');
                          next = focusable.eq(focusable.index(this) + 1);
                          if (next.length) {
                              //if disable try get next 10 fields
                              if (next.is(":disabled")){
                                  for(i=2;i<10;i++){
                                      next = focusable.eq(focusable.index(this) + i);
                                      if (!next.is(":disabled"))
                                          break;
                                  }
                              }
                              next.focus();
                          }
                          return false;
                      }
                  });
              }
              $("form").enterkeytab();
          });
          

          【讨论】:

            【解决方案10】:

            Vanilla js 支持 Shift + Enter 并能够选择哪些 HTML 标签是可聚焦的。应该可以在 IE9+ 上运行。

              onKeyUp(e) {
                switch (e.keyCode) {
                  case 13: //Enter
                    var focusableElements = document.querySelectorAll('input, button')
                    var index = Array.prototype.indexOf.call(focusableElements, document.activeElement)
                    if(e.shiftKey)
                      focus(focusableElements, index - 1)
                    else
                      focus(focusableElements, index + 1)
            
                    e.preventDefault()
                    break;
                }
                function focus(elements, index) {
                  if(elements[index])
                    elements[index].focus()
                }
              }
            

            【讨论】:

              【解决方案11】:

              我想出的最简单的香草JS sn-p:

              document.addEventListener('keydown', function (event) {
                if (event.keyCode === 13 && event.target.nodeName === 'INPUT') {
                  var form = event.target.form;
                  var index = Array.prototype.indexOf.call(form, event.target);
                  form.elements[index + 1].focus();
                  event.preventDefault();
                }
              });
              

              适用于 IE 9+ 和现代浏览器。

              【讨论】:

              • 我相信这应该是正确的答案。 OP 没有要求 jquery,这更简单,更兼容。
              • 不知道为什么这么多答案都假设存在表单...这不起作用:Uncaught TypeError: Array.prototype.indexOf called on null or undefined
              • 我如何使用此代码,但只能使用文本框而不是所有输入?
              【解决方案12】:

              在所有这些情况下,仅适用于 Chrome 和 IE,我添加了以下代码来解决该问题:

              var key = (window.event) ? e.keyCode : e.which;

              我测试了 keycode 是否等于 13 的键值

                  $('body').on('keydown', 'input, select, textarea', function (e) {
                  var self = $(this)
                    , form = self.parents('form:eq(0)')
                    , focusable
                    , next
                  ;
              
                  var key = (window.event) ? e.keyCode : e.which;
              
                  if (key == 13) {
                      focusable = form.find('input,a,select,button,textarea').filter(':visible');
                      next = focusable.eq(focusable.index(this) + 1);
                      if (next.length) {
                          next.focus();
                      } else {
                          focusable.click();
                      }
                      return false;
                  }
              });
              

              【讨论】:

                【解决方案13】:

                如果可以的话,我会重新考虑这样做:在表单中按 &lt;Enter&gt; 的默认操作会提交表单,并且您为更改此默认操作/预期行为所做的任何事情都可能导致网站出现一些可用性问题。

                【讨论】:

                • 通常我会同意,但我们的应用程序允许用户为他们自己的帐户单独设置这样的东西,并且客户为此提供资金,所以我认为我们没有理由坚持自己的立场。
                • 除了回车键的默认行为已经不一致。它仅在您使用文本输入类型时提交,大多数其他输入类型都有自己定义的回车键行为。只要他没有将 tab 键映射到其他东西,这似乎是一个比开箱即用的奇怪行为更好的解决方案。
                • 我发现按回车键提交不是预期的,实际上非常烦人。事实上,在我建立的每一个网站中,客户都要求我改变这种行为,因为它是不需要的。我责怪某个 [cough]Microsoft[/cough] 面对压倒性的证据表明这是不想要的,他们无法承认他们为这种持续的行为做出了错误的选择。
                【解决方案14】:

                映射 [Enter] 键以像 [Tab] 键一样工作

                我已经用 jQuery 重写了 Andre Van Zuydam 的答案,这对我不起作用。这会捕获 EnterShift+EnterEnter 制表符向前,Shift+Enter 制表符向后。

                我还重写了 self 由当前焦点项初始化的方式。表格也是这样选择的。代码如下:

                // Map [Enter] key to work like the [Tab] key
                // Daniel P. Clark 2014
                
                // Catch the keydown for the entire document
                $(document).keydown(function(e) {
                
                  // Set self as the current item in focus
                  var self = $(':focus'),
                      // Set the form by the current item in focus
                      form = self.parents('form:eq(0)'),
                      focusable;
                
                  // Array of Indexable/Tab-able items
                  focusable = form.find('input,a,select,button,textarea,div[contenteditable=true]').filter(':visible');
                
                  function enterKey(){
                    if (e.which === 13 && !self.is('textarea,div[contenteditable=true]')) { // [Enter] key
                
                      // If not a regular hyperlink/button/textarea
                      if ($.inArray(self, focusable) && (!self.is('a,button'))){
                        // Then prevent the default [Enter] key behaviour from submitting the form
                        e.preventDefault();
                      } // Otherwise follow the link/button as by design, or put new line in textarea
                
                      // Focus on the next item (either previous or next depending on shift)
                      focusable.eq(focusable.index(self) + (e.shiftKey ? -1 : 1)).focus();
                
                      return false;
                    }
                  }
                  // We need to capture the [Shift] key and check the [Enter] key either way.
                  if (e.shiftKey) { enterKey() } else { enterKey() }
                });
                

                原因textarea

                被包含是因为我们“”想要进入它。此外,一旦进入,我们不想阻止 Enter 的默认行为插入新行。

                原因abutton

                允许默认操作,“and”仍然专注于下一项,因为它们并不总是加载另一个页面。可以对诸如手风琴或选项卡式内容之类的内容产生触发/影响。因此,一旦您触发了默认行为,并且页面产生了特殊效果,您仍然希望转到下一项,因为您的触发器可能已经很好地介绍了它。

                【讨论】:

                • 最后一位:if (e.shiftKey) { enterKey() } else { enterKey() } 的目的是什么?似乎应该只是:enterKey().
                • @AVProgrammer 要让 entertab 一样,如果按住 shift 键,它需要反向运行。您询问的行允许在按下 shift 键时检查 enter 键。
                • 在这两种情况下检查 e.shiftKey 并调用 enterKey 是没有意义的。
                • @JeppeAndreasen 如果您希望它表现得像制表符,那么可以。因为 Shift+Tab 是反方向的。
                • 无论是否按下 shift,您都在执行相同的操作。所以 if 语句是不必要的,正如 avprogrammer 也指出的那样
                【解决方案15】:

                这里给出的所有实现都存在问题。有些不能正常使用 textareas 和提交按钮,大多数不允许您使用 shift 向后退,如果您有它们,它们都不会使用 tabindexes,并且它们都不会从最后一个到第一个或第一个环绕到最后。

                要使 [enter] 键的作用类似于 [tab] 键,但仍可正常使用文本区域和提交按钮,请使用以下代码。此外,此代码允许您使用 shift 键向后移动,并且制表符从前到后和从后到前环绕。

                源码:https://github.com/mikbe/SaneEnterKey

                咖啡脚本

                mbsd_sane_enter_key = ->
                  input_types = "input, select, button, textarea"
                  $("body").on "keydown", input_types, (e) ->
                    enter_key = 13
                    tab_key = 9
                
                    if e.keyCode in [tab_key, enter_key]
                      self = $(this)
                
                      # some controls should just press enter when pressing enter
                      if e.keyCode == enter_key and (self.prop('type') in ["submit", "textarea"])
                        return true
                
                      form = self.parents('form:eq(0)')
                
                      # Sort by tab indexes if they exist
                      tab_index = parseInt(self.attr('tabindex'))
                      if tab_index
                        input_array = form.find("[tabindex]").filter(':visible').sort((a,b) -> 
                          parseInt($(a).attr('tabindex')) - parseInt($(b).attr('tabindex'))
                        )
                      else
                        input_array = form.find(input_types).filter(':visible')
                
                      # reverse the direction if using shift
                      move_direction = if e.shiftKey then -1 else 1
                      new_index = input_array.index(this) + move_direction
                
                      # wrap around the controls
                      if new_index == input_array.length
                        new_index = 0
                      else if new_index == -1
                        new_index = input_array.length - 1
                
                      move_to = input_array.eq(new_index)
                      move_to.focus()
                      move_to.select()
                
                      false
                
                $(window).on 'ready page:load', ->
                  mbsd_sane_enter_key()
                

                JavaScript

                var mbsd_sane_enter_key = function() {
                  var input_types;
                  input_types = "input, select, button, textarea";
                
                  return $("body").on("keydown", input_types, function(e) {
                    var enter_key, form, input_array, move_direction, move_to, new_index, self, tab_index, tab_key;
                    enter_key = 13;
                    tab_key = 9;
                
                    if (e.keyCode === tab_key || e.keyCode === enter_key) {
                      self = $(this);
                
                      // some controls should react as designed when pressing enter
                      if (e.keyCode === enter_key && (self.prop('type') === "submit" || self.prop('type') === "textarea")) {
                        return true;
                      }
                
                      form = self.parents('form:eq(0)');
                
                      // Sort by tab indexes if they exist
                      tab_index = parseInt(self.attr('tabindex'));
                      if (tab_index) {
                        input_array = form.find("[tabindex]").filter(':visible').sort(function(a, b) {
                          return parseInt($(a).attr('tabindex')) - parseInt($(b).attr('tabindex'));
                        });
                      } else {
                        input_array = form.find(input_types).filter(':visible');
                      }
                
                      // reverse the direction if using shift
                      move_direction = e.shiftKey ? -1 : 1;
                      new_index = input_array.index(this) + move_direction;
                
                      // wrap around the controls
                      if (new_index === input_array.length) {
                        new_index = 0;
                      } else if (new_index === -1) {
                        new_index = input_array.length - 1;
                      }
                
                      move_to = input_array.eq(new_index);
                      move_to.focus();
                      move_to.select();
                      return false;
                    }
                  });
                };
                
                $(window).on('ready page:load', function() {
                  mbsd_sane_enter_key();
                }
                

                【讨论】:

                  【解决方案16】:

                  这是一个 angular.js 指令,可以使用其他答案作为灵感,让 enter 进入下一个字段。这里有一些看起来很奇怪的代码,因为我只使用 angular 打包的 jQlite。我相信这里的大部分功能都适用于所有浏览器 > IE8。

                  angular.module('myapp', [])
                  .directive('pdkNextInputOnEnter', function() {
                      var includeTags = ['INPUT', 'SELECT'];
                  
                      function link(scope, element, attrs) {
                          element.on('keydown', function (e) {
                              // Go to next form element on enter and only for included tags
                              if (e.keyCode == 13 && includeTags.indexOf(e.target.tagName) != -1) {
                                  // Find all form elements that can receive focus
                                  var focusable = element[0].querySelectorAll('input,select,button,textarea');
                  
                                  // Get the index of the currently focused element
                                  var currentIndex = Array.prototype.indexOf.call(focusable, e.target)
                  
                                  // Find the next items in the list
                                  var nextIndex = currentIndex == focusable.length - 1 ? 0 : currentIndex + 1;
                  
                                  // Focus the next element
                                  if(nextIndex >= 0 && nextIndex < focusable.length)
                                      focusable[nextIndex].focus();
                  
                                  return false;
                              }
                          });
                      }
                  
                      return {
                          restrict: 'A',
                          link: link
                      };
                  });
                  

                  这是我在我正在开发的应用程序中使用它的方法,只需在元素上添加pdk-next-input-on-enter 指令。我正在使用条形码扫描仪将数据输入字段,扫描仪的默认功能是模拟键盘,在输入扫描的条形码数据后注入回车键。

                  此代码有一个副作用(对我的用例来说是积极的),如果它将焦点移到按钮上,enter keyup 事件将导致按钮的操作被激活。这对我的流程非常有效,因为我的标记中的最后一个表单元素是一个按钮,一旦通过扫描条形码“标记”了所有字段,我希望激活该按钮。

                  <!DOCTYPE html>
                  <html ng-app=myapp>
                    <head>
                        <script src="angular.min.js"></script>
                        <script src="controller.js"></script>
                    </head>
                    <body ng-controller="LabelPrintingController">
                        <div class='.container' pdk-next-input-on-enter>
                            <select ng-options="p for p in partNumbers" ng-model="selectedPart" ng-change="selectedPartChanged()"></select>
                            <h2>{{labelDocument.SerialNumber}}</h2>
                            <div ng-show="labelDocument.ComponentSerials">
                                <b>Component Serials</b>
                                <ul>
                                    <li ng-repeat="serial in labelDocument.ComponentSerials">
                                        {{serial.name}}<br/>
                                        <input type="text" ng-model="serial.value" />
                                    </li>
                                </ul>
                            </div>
                            <button ng-click="printLabel()">Print</button>
                        </div>
                    </body>
                  </html>
                  

                  【讨论】:

                    【解决方案17】:

                    谢谢你的好剧本。

                    我刚刚在上面的函数上添加了 shift 事件以在元素之间返回,我想有人可能需要这个。

                    $('body').on('keydown', 'input, select, textarea', function(e) {
                    var self = $(this)
                      , form = self.parents('form:eq(0)')
                      , focusable
                      , next
                      , prev
                      ;
                    
                    if (e.shiftKey) {
                     if (e.keyCode == 13) {
                         focusable =   form.find('input,a,select,button,textarea').filter(':visible');
                         prev = focusable.eq(focusable.index(this)-1); 
                    
                         if (prev.length) {
                            prev.focus();
                         } else {
                            form.submit();
                        }
                      }
                    }
                      else
                    if (e.keyCode == 13) {
                        focusable = form.find('input,a,select,button,textarea').filter(':visible');
                        next = focusable.eq(focusable.index(this)+1);
                        if (next.length) {
                            next.focus();
                        } else {
                            form.submit();
                        }
                        return false;
                    }
                    });
                    

                    【讨论】:

                    【解决方案18】:

                    你可以使用下面我的代码,在 Mozilla、IE 和 Chrome 中测试过

                       // Use to act like tab using enter key
                        $.fn.enterkeytab=function(){
                             $(this).on('keydown', 'input, select,', function(e) {
                            var self = $(this)
                              , form = self.parents('form:eq(0)')
                              , focusable
                              , next
                              ;
                                if (e.keyCode == 13) {
                                    focusable = form.find('input,a,select,button').filter(':visible');
                                    next = focusable.eq(focusable.index(this)+1);
                                    if (next.length) {
                                        next.focus();
                                    } else {
                                        alert("wd");
                                        //form.submit();
                                    }
                                    return false;
                                }
                            });
                    
                        }
                    

                    如何使用?

                    $("#form").enterkeytab(); // 进入键标签

                    【讨论】:

                      【解决方案19】:

                      我将 OPs 解决方案重新设计为 Knockout 绑定,并认为我会分享它。非常感谢:-)

                      Here's小提琴

                      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                      <html xmlns="http://www.w3.org/1999/xhtml" >
                      <head>
                          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
                          <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js" type="text/javascript"></script>
                      
                      
                      </head>
                      <body>
                      
                          <div data-bind="nextFieldOnEnter:true">
                              <input type="text" />
                              <input type="text" />
                              <select>
                                <option value="volvo">Volvo</option>
                                <option value="saab">Saab</option>
                                <option value="mercedes">Mercedes</option>
                                <option value="audi">Audi</option>
                              </select>
                              <input type="text" />
                              <input type="text" />
                          </div>
                      
                      
                          <script type="text/javascript">
                          ko.bindingHandlers.nextFieldOnEnter = {
                              init: function(element, valueAccessor, allBindingsAccessor) {
                                  $(element).on('keydown', 'input, select', function (e) {
                                      var self = $(this)
                                      , form = $(element)
                                        , focusable
                                        , next
                                      ;
                                      if (e.keyCode == 13) {
                                          focusable = form.find('input,a,select,button,textarea').filter(':visible');
                                          var nextIndex = focusable.index(this) == focusable.length -1 ? 0 : focusable.index(this) + 1;
                                          next = focusable.eq(nextIndex);
                                          next.focus();
                                          return false;
                                      }
                                  });
                              }
                          };
                      
                          ko.applyBindings({});
                          </script>
                      </body>
                      </html>
                      

                      【讨论】:

                      • 您的解决方案正是我想要的,但有一个例外:我不希望在输入类型按钮时出现这种行为。我怎样才能排除它们?我设法将按钮定义为
                      • 嗨。也许尝试如下更改选择器? .... $(element).on('keydown', 'input:not(input[type=button]), select', function (e) {.....
                      • +1;这很好,我经常使用淘汰赛,但我需要这个功能的项目是一个 AngularJS 应用程序。如果您不介意,我将借用您的 impl 代码并使用 Angular 的自定义指令发布答案。
                      • 一切都很甜蜜。当您了解它们时,自定义绑定非常棒。 :-)
                      【解决方案20】:

                      我让它只在 JavaScript 中工作。 Firefox 不会让您更新 keyCode,因此您所能做的就是捕获 keyCode 13 并强制它通过 tabIndex 将注意力集中在下一个元素上,就像按下 keyCode 9 一样。棘手的部分是找到下一个 tabIndex。我仅在 IE8-IE10 和 Firefox 上对此进行了测试,并且可以正常工作:

                      function ModifyEnterKeyPressAsTab(event)
                      {
                          var caller;
                          var key;
                          if (window.event)
                          {
                              caller = window.event.srcElement; //Get the event caller in IE.
                              key = window.event.keyCode; //Get the keycode in IE.
                          }
                          else
                          {
                              caller = event.target; //Get the event caller in Firefox.
                              key = event.which; //Get the keycode in Firefox.
                          }
                          if (key == 13) //Enter key was pressed.
                          {
                              cTab = caller.tabIndex; //caller tabIndex.
                              maxTab = 0; //highest tabIndex (start at 0 to change)
                              minTab = cTab; //lowest tabIndex (this may change, but start at caller)
                              allById = document.getElementsByTagName("input"); //Get input elements.
                              allByIndex = []; //Storage for elements by index.
                              c = 0; //index of the caller in allByIndex (start at 0 to change)
                              i = 0; //generic indexer for allByIndex;
                              for (id in allById) //Loop through all the input elements by id.
                              {
                                  allByIndex[i] = allById[id]; //Set allByIndex.
                                  tab = allByIndex[i].tabIndex;
                                  if (caller == allByIndex[i])
                                      c = i; //Get the index of the caller.
                                  if (tab > maxTab)
                                      maxTab = tab; //Get the highest tabIndex on the page.
                                  if (tab < minTab && tab >= 0)
                                      minTab = tab; //Get the lowest positive tabIndex on the page.
                                  i++;
                              }
                              //Loop through tab indexes from caller to highest.
                              for (tab = cTab; tab <= maxTab; tab++)
                              {
                                  //Look for this tabIndex from the caller to the end of page.
                                  for (i = c + 1; i < allByIndex.length; i++)
                                  {
                                      if (allByIndex[i].tabIndex == tab)
                                      {
                                          allByIndex[i].focus(); //Move to that element and stop.
                                          return;
                                      }
                                  }
                                  //Look for the next tabIndex from the start of page to the caller.
                                  for (i = 0; i < c; i++)
                                  {
                                      if (allByIndex[i].tabIndex == tab + 1)
                                      {
                                          allByIndex[i].focus(); //Move to that element and stop.
                                          return;
                                      }
                                  }
                                  //Continue searching from the caller for the next tabIndex.
                              }
                      
                              //The caller was the last element with the highest tabIndex,
                              //so find the first element with the lowest tabIndex.
                              for (i = 0; i < allByIndex.length; i++)
                              {
                                  if (allByIndex[i].tabIndex == minTab)
                                  {
                                      allByIndex[i].focus(); //Move to that element and stop.
                                      return;
                                  }
                              }
                          }
                      }
                      

                      要使用此代码,请将其添加到您的 html 输入标签中:

                      <input id="SomeID" onkeydown="ModifyEnterKeyPressAsTab(event);" ... >
                      

                      或者将其添加到javascript中的元素中:

                      document.getElementById("SomeID").onKeyDown = ModifyEnterKeyPressAsTab;
                      

                      其他几点说明:

                      我只需要它来处理我的输入元素,但如果需要,您可以将它扩展到其他文档元素。为此,getElementsByClassName 非常有帮助,但那完全是另一回事了。

                      一个限制是它只能在您添加到 allById 数组的元素之间使用制表符。它不会围绕您的浏览器可能的其他内容进行选项卡,例如 html 文档之外的工具栏和菜单。也许这是一个功能而不是限制。如果您愿意,请捕获 keyCode 9,此行为也适用于 tab 键。

                      【讨论】:

                        【解决方案21】:

                        更改此行为实际上创建了比本机实现的默认行为更好的用户体验。考虑回车键的行为从用户的角度来看已经不一致,因为在单行输入中,回车倾向于提交表单,而在多行文本区域中,它只是在内容中添加换行符字段。

                        我最近是这样做的(使用 jQuery):

                        $('input.enterastab, select.enterastab, textarea.enterastab').live('keydown', function(e) {
                         if (e.keyCode==13) {
                          var focusable = $('input,a,select,button,textarea').filter(':visible');
                          focusable.eq(focusable.index(this)+1).focus();
                          return false;
                         }
                        });
                        

                        这不是非常有效,但运行良好且可靠 - 只需将“enterastab”类添加到任何应该以这种方式运行的输入元素。

                        【讨论】:

                        • 简明扼要!从类似的东西开始,但现在我已经对其进行了扩展 - 请参阅我的答案(在此页面上)PlusAsTab
                        • 正在专门寻找一些可以窃取的东西,这些东西被认为是不可见的领域。我发现的大多数其他解决方案都没有。谢谢
                        【解决方案22】:

                        我也有类似的需求。 这是我所做的:

                          <script type="text/javascript" language="javascript">
                            function convertEnterToTab() {
                              if(event.keyCode==13) {
                                event.keyCode = 9;
                              }
                            }
                            document.onkeydown = convertEnterToTab;    
                          </script>  
                        

                        【讨论】:

                          【解决方案23】:

                          您可以在执行过程中以编程方式迭代添加 onkeydown 处理程序的表单元素。这样你就可以重用代码了。

                          【讨论】:

                          • 这就是我最终要做的。谢谢!
                          猜你喜欢
                          • 2019-08-30
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2019-04-27
                          • 1970-01-01
                          • 2022-08-17
                          • 2012-01-22
                          相关资源
                          最近更新 更多