在文本框中捕获TAB键 [英] Capturing TAB key in text box

查看:144
本文介绍了在文本框中捕获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键之前捕获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 + Tab ,或 Ctrl + 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库在其在IE和FF中工作的事件对象上提供 preventDefault 方法。

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>

这篇关于在文本框中捕获TAB键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆