捕获文本框中的 TAB 键

问题描述:

我希望能够在文本框中使用 Tab 键来跨越四个空格.现在的方式是,Tab 键将我的光标跳转到下一个输入.

I would like to be able to use the Tab key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input.

是否有一些 JavaScript 会在文本框中的 Tab 键冒泡到 UI 之前捕获它?

Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI?

我了解某些浏览器(即 FireFox)可能不允许这样做.像 Shift+TabCtrl+Q 这样的自定义组合键怎么样?

I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like Shift+Tab, or Ctrl+Q?

即使你捕获了 keydown/keyup 事件,这些也是唯一的 Tab 键事件触发,您仍然需要一些方法来防止发生默认操作,即移至 Tab 键顺序中的下一项.

Even if you capture the keydown/keyup event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring.

在 Firefox 中,您可以对传递给事件处理程序的事件对象调用 preventDefault() 方法.在 IE 中,您必须从事件句柄返回 false.JQuery 库为其事件对象提供了一个 preventDefault 方法,该方法适用于 IE 和 FF.

In Firefox you can call the preventDefault() method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a preventDefault method on its event object that works in IE and FF.

<body>
<input type="text" id="myInput">
<script type="text/javascript">
    var myInput = document.getElementById("myInput");
    if(myInput.addEventListener ) {
        myInput.addEventListener('keydown',this.keyHandler,false);
    } else if(myInput.attachEvent ) {
        myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
    }

    function keyHandler(e) {
        var TABKEY = 9;
        if(e.keyCode == TABKEY) {
            this.value += "    ";
            if(e.preventDefault) {
                e.preventDefault();
            }
            return false;
        }
    }
</script>
</body>