javascript - 查找文本区域中光标的位置

标签 javascript jquery google-chrome

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

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>

您必须在文本区域上按 TAB

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

想法?

最佳答案

相关于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);

关于javascript - 查找文本区域中光标的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6960445/

相关文章:

javascript - Jquery Removing pseudo element styles - 禁用 anchor unstyle anchor

WPF:如何在WPF/MVVM中制作Google Chrome样式的GUI?

android - SSL 证书不受信任 - 仅在移动设备上

javascript - 如何验证来自特定域的电子邮件地址?

javascript - 在异步函数中等待 MySQL 查询?

javascript - html5数据属性需要值吗?

javascript - history.createBrowserHistory 不是函数 - React js

javascript - Django 中的 Ajax POST 文件上传

jquery - 用 JS 添加一个 css 过渡,并同时更改作为过渡主题的属性,不起作用

node.js - 无服务器框架 : Chrome "Error: spawn ETXTBSY",