【问题标题】:Find position of cursor in textarea在文本区域中查找光标的位置
【发布时间】:2011-10-21 02:04:37
【问题描述】:

为什么这段代码不起作用?

http://sandbox.phpcode.eu/g/5db40.php

<form>
   <textarea></textarea>
</form>
<script>
$(function(){
    $("textarea").keydown(function(e){
        if (e.keyCode == 9){

                     $("textarea").selectionStart.append("    ");
                     e.preventDefault();
        }
    });
});
</script>

你必须在 textarea 上按 TAB

问题在于它不执行/附加四个空格,并且执行默认浏览器操作(在 Chrome 中切换到地址选项卡)

想法?

【问题讨论】:

  • 观察:即使是 Stack Overflow 的 textareas,通常包含缩进的代码,也不允许使用制表符。
  • @genesis:我不太清楚。我自己没有尝试过。但我的评论表明这可能是不可行的。

标签: javascript jquery google-chrome


【解决方案1】:

this相关的问题,试试:

$(function () {
    $("textarea").keydown(function (e) {
        if (e.keyCode == 9) {
            e.preventDefault();
            var $this = $(this);
            var pos = $this[0].selectionStart;
            $this.val($this.val().substring(0, pos) + "    " + $this.val().substring(pos));
            $this.setCursorPosition(pos + 4);
        }
    });
});

并从this 帖子中添加 JQuery。

new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);

【讨论】:

  • 这可能是因为append 不是javascript 字符串函数。尝试旧的string = string + 'extra stuff'; 方法。
  • 但这会在末尾附加这些空格。我想要它到指针的实际位置
  • 仍然切换到我的地址栏 tsandbox.phpcode.eu/g/81281.php
  • 那是因为 javascript 有错误。请参阅更正。
  • 有效,但不是我想要的。它将制表符附加到末尾,而不是实际的指针位置
【解决方案2】:

为了在 jQuery 中操作文本区域选择和插入符号位置,我建议使用 my jQuery plug-in 来执行此操作,它适用于所有主要浏览器,并提供获取和设置插入符号/选择位置、在插入符号位置插入内容等方法.你想要的代码是:

$("textarea").keydown(function(e) {
    if (e.keyCode == 9) {
        e.preventDefault();
        $(this).replaceSelectedText("    ");
    }
});

【讨论】:

  • 很好,我会看的。谢谢
【解决方案3】:
【解决方案4】:

试试这个,我敢肯定它会奏效。




【讨论】:

  • 请再次检查我的代码,我再次做了一些修改,现在在所有浏览器中都可以正常工作。
【解决方案5】:
var range = $(this).get(0).createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();

这 (JSFiddle) 是我能做到的最好的,但我无法让它在 Firefox 或 Chrome 上运行。如果有人设法在 Chrome 工作的情况下在 textarea 中按下按钮选择文本,请随时告诉我。

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 2023-03-15
    • 2010-09-25
    • 1970-01-01
    • 2023-03-02
    • 2011-12-21
    • 2011-07-09
    • 1970-01-01
    相关资源
    最近更新 更多