javascript 替换 IE 11 中的 keyCode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26438274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:57:58  来源:igfitidea点击:

Replace keyCode in IE 11

javascriptjqueryinternet-explorer-11

提问by Arian

We use this code for simulating Tabkey with Enterkey:

我们使用此代码来模拟TabEnter密钥的密钥:

function EnterTab() {
    if (event.keyCode == 13) event.keyCode = 9;
    return false;
}

But in IE 11 keyCodeis readonlyand this code does not work. How I can solve this problem that my code run in IE 11?

但在 IE 11 中keyCode只读的,这段代码不起作用。如何解决我的代码在 IE 11 中运行的问题?

采纳答案by Salman A

We use this code for simulating Tab key with Enter key:
...
When I hit Enter I want focus go to next control.

我们使用此代码来模拟带有 Enter 键的 Tab 键:
...
当我按下 Enter 键时,我希望焦点转到下一个控件。

The idea is wrong. Don't change enter to tab. Tackle this problem by intercepting the enter key, set the focus on next element and cancel the event. jQuery solution:

这个想法是错误的。不要将输入更改为选项卡。通过拦截回车键解决这个问题,将焦点设置在下一个元素上并取消事件。jQuery 解决方案:

$(function() {
  $("form").on("keypress", "input[type=text], select, textarea", function(e) {
    if (e.which === 13) {
      e.preventDefault();
      var $fields = $(this).closest("form").find(":input");
      var index = $fields.index(this);
      $fields.eq(index + 1).trigger("focus");
    }
  });
});
input,
select,
textarea {
  box-sizing: border-box;
  margin: .5em 0;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<form method="post">
  <p>Hitting enter inside the text fields will not submit the form</p>
  <textarea rows="4"></textarea>
  <input type="text" />
  <select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>
  <select>
    <option>A</option>
    <option>B</option>
    <option>C</option>
  </select>
  <input type="text" />
  <input type="submit" value="sumbmit" />
</form>

jsFiddle for testing in Internet Explorer

用于在 Internet Explorer 中进行测试的 jsFiddle

回答by James Donnelly

keyCodeshouldbe readonly in all modern browsers, simply because modifying it is hacky and unnecessary. Looking at the code you provided in your other question: keydown event does not fire correctly using jQuery trigger, we can imitate this functionality rather than attempt to return the altered event.

keyCode应该在所有现代浏览器中都是只读的,因为修改它很麻烦而且没有必要。查看您在其他问题中提供的代码:使用 jQuery trigger 无法正确触发 keydown 事件,我们可以模仿此功能而不是尝试返回更改的事件。

jQuery actually does let us modify the eventobject when it is passed in to a jQuery event handler. As you have jquerytagged, we can therefore make use of this in our answer, passing the modifications into a trigger()called on the same element.

jQuery 实际上确实让我们在将event对象传递给 jQuery 事件处理程序时对其进行修改。由于您已标记jquery,因此我们可以在答案中使用它,将修改传递到trigger()同一元素上的调用中。

if (e.which === 13) {
    // Alter the normalised e.which property
    e.which = 9;

    // Alter the default properties for good measure
    e.charCode = 9;
    e.keyCode = 9;

    $(this).trigger(e);
    return false;
}

Note: I've used e.whichrather than e.keyCodeas jQuery normalises this across all browsers.

注意:我使用e.which而不是e.keyCodejQuery 在所有浏览器中规范了这一点。

Here is a demo which shows this in action. If you press the Enterkey when the inputelement is in focus, the event will be replaced with the Tabevent:

这是一个演示,显示了这一点。如果Enterinput元素处于焦点时按下该键,则事件将替换为Tab事件:

var $input = $('input'),
    $p = $('p');

$input.on('keydown', function(e) {
    if (e.which == 13) {  
        $p.html($p.html() + 'Enter key intercepted, modifying 13 to 9.<br>');
                
        e.which = 9;
      
        e.charCode = 9;
        e.keyCode = 9;
      
        $(this).trigger(e);
      
        return false;
    }
  
    $p.html($p.html() + 'Key pressed: ' + e.keyCode + '<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<p></p>

As I've mentioned in my answer here, just because you're changing the event doesn't mean your browser is then going to handle it as if the Tabkey has been pressed. The logging lets us know that our event has successfully been intercepted and changedfrom Enterto Tab, even on Internet Explorer 11.

正如我在此处的回答中提到的,仅仅因为您正在更改事件并不意味着您的浏览器会像Tab按下键一样处理它。日志记录让我们知道我们的事件已成功被拦截并从更改EnterTab,即使在 Internet Explorer 11 上也是如此。

IE11 Example

IE11 示例

回答by Giannis Grivas

This worked in IE9 but no longer works in IE11.So you have to find a solution that stimulates the result you want.For example, if you want to allow users to press 'Enter'to go to the next data entry field (like tab does), try something like this.

这在 IE9 中有效,但在 IE11 中不再有效。所以你必须找到一个刺激你想要的结果的解决方案。例如,如果你想让用户按下'Enter'进入下一个数据输入字段(就像 tab 一样),尝试这样的事情。

var i = 0;
var els = myform.getElementsByTagName('input').length
document.onkeydown = function(e) {
  e = e || window.event;
  if (e.keyCode == 13) {
    i++;
    i > els - 1 ? i = 0 : i = i;
    document.myform[i].focus();

  }
};
<span>Press 'enter' inside text to act like tab button</span>
<form name="myform">
  <input type="text">
  <input type="text">
  <input type="text">
</form>

jQuery Example:

jQuery 示例:

$('.info').bind('keypress', function(event) {
  if (event.which === 13) {
    var nextItem = $(this).next('.info');

    if (nextItem.size() === 0) {
      nextItem = $('.info').eq(0);
    }
    nextItem.focus();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="info" />
<input type="text" class="info" />
<input type="text" class="info" />

回答by Rembunator

You can just select the next or previous form element after catching the Enter key.

您可以在按下 Enter 键后选择下一个或上一个表单元素。

This will catch all possible form elements. Pressing shift-Enter will move the focus to the previous form element.

这将捕获所有可能的表单元素。按 shift-Enter 会将焦点移动到上一个表单元素。

Pressing Enter on the submit button will still submit the form. Pressing shift-Enter will focus the previous form element.

在提交按钮上按 Enter 键仍将提交表单。按 shift-Enter 将聚焦前一个表单元素。

function EnterTabTest(event) 
    {
    if (!event.shiftKey && (event.target.getAttribute('type')=='submit')) return true;

    event.preventDefault();
    if (event.keyCode == 13)
        {
            if (event.shiftKey)
                $(event.target).prevAll(":input").first().focus();
            else
                $(event.target).nextAll(':input').first().focus();
        }
    return false;
    }


<form onkeydown='EnterTabTest(event)'>
    <input type='text' />
    <input type='text' />
    <input type='text' />
    <p>not part of the form</p>
    <select>
        <option>opt1</option>
        <option>opt2</option>
    </select>
    <p>also not part of the form</p>
    <input type='text' />
    <input type='submit' />

</form>

Here is a fiddle so you can try

这是一个小提琴,所以你可以试试

It also works in IE11, I tried.

它也适用于 IE11,我试过了。