jQuery在文本区域中设置光标位置

本小妞迷上赌 提交于 2020-02-26 19:27:28

如何使用jQuery在文本字段中设置光标位置? 我有一个带有内容的文本字段,我希望用户将光标放在该字段上时将光标定位在某个偏移处。 该代码应该看起来像这样:

$('#input').focus(function() {
  $(this).setCursorPosition(4);
});

该setCursorPosition函数的实现是什么样的? 如果您的文本字段的内容为abcdefg,则此调用将导致光标的定位如下:abcd ** | ** efg。

Java具有类似的功能setCaretPosition。 javascript是否存在类似的方法?

更新:我修改了CMS的代码以与jQuery配合使用,如下所示:

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

#1楼

对我在bitbucket中找到的代码进行小的修改

如果给定2个位置,代码现在可以选择/突出显示起点/终点。 经过测试,在FF / Chrome / IE9 / Opera中运行正常。

$('#field').caret(1, 9);

下面列出了代码,仅更改了几行:

(function($) {
  $.fn.caret = function(pos) {
    var target = this[0];
    if (arguments.length == 0) { //get
      if (target.selectionStart) { //DOM
        var pos = target.selectionStart;
        return pos > 0 ? pos : 0;
      }
      else if (target.createTextRange) { //IE
        target.focus();
        var range = document.selection.createRange();
        if (range == null)
            return '0';
        var re = target.createTextRange();
        var rc = re.duplicate();
        re.moveToBookmark(range.getBookmark());
        rc.setEndPoint('EndToStart', re);
        return rc.text.length;
      }
      else return 0;
    }

    //set
    var pos_start = pos;
    var pos_end = pos;

    if (arguments.length > 1) {
        pos_end = arguments[1];
    }

    if (target.setSelectionRange) //DOM
      target.setSelectionRange(pos_start, pos_end);
    else if (target.createTextRange) { //IE
      var range = target.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos_end);
      range.moveStart('character', pos_start);
      range.select();
    }
  }
})(jQuery)

#2楼

在将文本插入到文本区域之前设置焦点吗?

$("#comments").focus();
$("#comments").val(comments);

#3楼

我正在使用这个: http : //plugins.jquery.com/project/jCaret


#4楼

这对我适用于Chrome

$('#input').focus(function() {
    setTimeout( function() {
        document.getElementById('input').selectionStart = 4;
        document.getElementById('input').selectionEnd = 4;
    }, 1);
});

显然,您需要一个微秒或更长时间的延迟,因为通常用户会通过单击要覆盖的文本字段中的某个位置(或单击选项卡)来关注文本字段,因此必须等到该位置由用户设置,然后单击更改。


#5楼

我确实意识到这是一篇很老的文章,但是我认为我应该提供一个也许更简单的解决方案来仅使用jQuery更新它。

function getTextCursorPosition(ele) {   
    return ele.prop("selectionStart");
}

function setTextCursorPosition(ele,pos) {
    ele.prop("selectionStart", pos + 1);
    ele.prop("selectionEnd", pos + 1);
}

function insertNewLine(text,cursorPos) {
    var firstSlice = text.slice(0,cursorPos);
    var secondSlice = text.slice(cursorPos);

    var new_text = [firstSlice,"\n",secondSlice].join('');

    return new_text;
}

使用ctrl-enter添加新行的用法(例如在Facebook中):

$('textarea').on('keypress',function(e){
    if (e.keyCode == 13 && !e.ctrlKey) {
        e.preventDefault();
        //do something special here with just pressing Enter
    }else if (e.ctrlKey){
        //If the ctrl key was pressed with the Enter key,
        //then enter a new line break into the text
        var cursorPos = getTextCursorPosition($(this));                

        $(this).val(insertNewLine($(this).val(), cursorPos));
        setTextCursorPosition($(this), cursorPos);
    }
});

我愿意接受批评。 谢谢。

更新:此解决方案不允许正常的复制和粘贴功能(即ctrl-c,ctrl-v)起作用,因此以后我将必须对其进行编辑以确保该部分再次起作用。 如果您有想法,请在此处评论,我们将很乐意对其进行测试。 谢谢。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!