本文介绍了jQuery中的按键:在TEXTAREA中按Tab(在编辑现有文本时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在TEXTAREA中插入TAB字符,如下所示:

I want to insert TAB characters inside a TEXTAREA, like this:

<textarea>{KEYPRESS-INSERTS-TAB-HERE}Hello World</textarea>

我可以在现有TEXTAREA文本之前/之后插入 -我可以在TEXTAREA中插入/替换所有文本-但尚未能够插入在现有的TEXTAREA文本中(通过光标)在内部.

I can insert before/after the existing TEXTAREA text - and I can insert / replace all text in the TEXTAREA - but have not yet been able to insert inside the existing TEXTAREA text (by the cursor) in a simple way.

$('textarea:input').live('keypress', function(e) {
    if (e.keyCode == 9) {
        e.preventDefault();

        // Press TAB to append a string (keeps the original TEXTAREA text).
        $(this).append("TAB TAB TAB AFTER TEXTAREA TEXT");

        // Press TAB to append a string (keeps the original TEXTAREA text).
        $(this).focus().prepend("TAB TAB TAB BEFORE TEXTAREA TEXT");

        // Press TAB to replace a all text inside TEXTAREA.
        $(this).val("INSERT INTO TEXTAREA / REPLACE EXISTING TEXT");

    }
});

有一个jQuery的"tabs in textarea"插件("Tabby" ) -但这是254条代码行-我希望只输入几行代码.

There is a "tabs in textarea" plug-in for jQuery ("Tabby") - but it's 254 code lines - I was hoping for just a few lines of code.

我研究了一些链接:(同样,我希望使用更少的代码行).

A few links that I studied: (again, I would prefer fewer code lines).

http://www.dynamicdrive.com/forums/showthread.php? t = 34452
http://www.webdeveloper.com/forum/showthread.php?t=32317
http://pallieter.org/Projects/insertTab/

http://www.dynamicdrive.com/forums/showthread.php?t=34452
http://www.webdeveloper.com/forum/showthread.php?t=32317
http://pallieter.org/Projects/insertTab/

请告知.谢谢.

推荐答案

我正在为自己创建一个基于AJAX的简单IDE,以便可以快速测试PHP代码段.

I was creating a AJAX powered simple IDE for myself so I can rapidly test out PHP snippets.

我记得遇到过同样的问题,这是我解决的方法:

I remember stumbling upon the same problem, here's how I solved it:

$('#input').keypress(function (e) {
    if (e.keyCode == 9) {
        var myValue = "\t";
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos,this.value.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;

        e.preventDefault();
    }
});

#input是文本区域的ID.

该代码不是完全属于我的,我在Google的某个地方找到了它.

The code is not completely mine, I found it on Google somewhere.

我只在FF 3.5和IE7上进行过测试.遗憾的是,它在IE7上不起作用.

I've only tested it on FF 3.5 and IE7. It does not work on IE7 sadly.

这篇关于jQuery中的按键:在TEXTAREA中按Tab(在编辑现有文本时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 12:22