如何处理< tab>在textarea? [英] How to handle <tab> in textarea?

查看:134
本文介绍了如何处理< tab>在textarea?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个textarea来处理按 tab 键的情况。



在默认情况下,如果您按下标签键然后焦点离开textarea。但是,当用户想要在textarea中键入 tab 键时,情况如何?

我可以捕获此事件并将焦点返回到textarea并添加您可以: 光标位置的标签

//jsfiddle.net/sdDVf/8/\">http://jsfiddle.net/sdDVf/8/






  $(textarea)。keydown(function(e){
if(e.keyCode === 9){// tab tabb
//获取插入位置/选择
var start = this.selectionStart;
var end = this.selectionEnd;

var $ this = $(this);
var value = $ this.val();

//将textarea的值设置为:caret前的文本+ caret后的tab +文本
$ this.val(value.substring(0 ,开始)
+\ t
+ value.substring(end));

//将插入符号再次放在正确位置(为制表符添加一个)
T his.selectionStart = this.selectionEnd = start + 1;

//防止焦点丢失
e.preventDefault();
}
});


I would like a textarea that handles a situation of pressing tab key.

In default case if you press a tab key then focus leaves the textarea. But what about the situation when user wants to type tab key in textarea?

Can I catch this event and return focus to the textarea and add a tab to a current cursor position?

解决方案

You can: http://jsfiddle.net/sdDVf/8/.


$("textarea").keydown(function(e) {
    if(e.keyCode === 9) { // tab was pressed
        // get caret position/selection
        var start = this.selectionStart;
        var end = this.selectionEnd;

        var $this = $(this);
        var value = $this.val();

        // set textarea value to: text before caret + tab + text after caret
        $this.val(value.substring(0, start)
                    + "\t"
                    + value.substring(end));

        // put caret at right position again (add one for the tab)
        this.selectionStart = this.selectionEnd = start + 1;

        // prevent the focus lose
        e.preventDefault();
    }
});

这篇关于如何处理< tab>在textarea?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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