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

jcn*_*ghm 434 html javascript jquery textfield

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

$('#input').focus(function() {
  $(this).setCursorPosition(4);
});
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

mpe*_*pen 298

这是一个jQuery解决方案:

$.fn.selectRange = function(start, end) {
    if(end === undefined) {
        end = start;
    }
    return this.each(function() {
        if('selectionStart' in this) {
            this.selectionStart = start;
            this.selectionEnd = end;
        } else if(this.setSelectionRange) {
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

有了这个,你就可以做到

$('#elem').selectRange(3,5); // select a range of text
$('#elem').selectRange(3); // set cursor position
Run Code Online (Sandbox Code Playgroud)

  • @Jesse:Dunno怎么回事,我平时用4.固定. (2认同)
  • 我需要事先添加`$('#elem').focus()`来显示闪烁的光标. (2认同)

CMS*_*CMS 253

我有两个功能:

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用setCaretToPos:

setCaretToPos(document.getElementById("YOURINPUT"), 4);
Run Code Online (Sandbox Code Playgroud)

带有a textarea和an的实例input,显示了jQuery的用法:

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  } else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos(input, pos) {
  setSelectionRange(input, pos, pos);
}

$("#set-textarea").click(function() {
  setCaretToPos($("#the-textarea")[0], 10)
});
$("#set-input").click(function() {
  setCaretToPos($("#the-input")[0], 10);
});
Run Code Online (Sandbox Code Playgroud)
<textarea id="the-textarea" cols="40" rows="4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
<br><input type="button" id="set-textarea" value="Set in textarea">
<br><input id="the-input" type="text" size="40" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit">
<br><input type="button" id="set-input" value="Set in input">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

截至2016年,测试并在Chrome,火狐,IE11,甚至IE8的工作(见去年在这里 ;栈片断不支持IE8).

  • 为什么崩溃(真实)是必要的,因为你要设置结束并开始选择偏移? (3认同)

HRJ*_*HRJ 37

这里的解决方案是正确的,除了jQuery扩展代码.

扩展函数应迭代每个选定的元素并返回this支持链接.这是 一个正确的版本:

$.fn.setCursorPosition = function(pos) {
  this.each(function(index, elem) {
    if (elem.setSelectionRange) {
      elem.setSelectionRange(pos, pos);
    } else if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  });
  return this;
};
Run Code Online (Sandbox Code Playgroud)

  • 每个函数返回jquery对象.所以你可以这样做:`return this.each(function ...)`并删除独立行. (3认同)

AVP*_*mer 22

我发现了一个适合我的解决方案:

$.fn.setCursorPosition = function(position){
    if(this.length == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    if(this.length == 0) return this;
    var input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
}

$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
            return this;
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以通过调用将焦点移动到任何元素的结尾:

$(element).focusEnd();
Run Code Online (Sandbox Code Playgroud)

  • 对于textarea元素,对focusEnd的改进是添加`this.scrollTop(this [0] .scrollHeight);`,以确保滚动textarea以使插入点可见. (3认同)

Bob*_*ris 10

这适用于Mac OSX上的Safari 5,jQuery 1.4:

$("Selector")[elementIx].selectionStart = desiredStartPos; 
$("Selector")[elementIx].selectionEnd = desiredEndPos;
Run Code Online (Sandbox Code Playgroud)


tof*_*ius 8

我确实意识到这是一篇非常古老的帖子,但我认为我应该提供一个更简单的解决方案来仅使用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;
}
Run Code Online (Sandbox Code Playgroud)

使用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);
    }
});
Run Code Online (Sandbox Code Playgroud)

我很乐意批评.谢谢.

更新:此解决方案不允许正常的复制和粘贴功能(即ctrl-c,ctrl-v),所以我将来必须编辑它以确保该部分再次工作.如果你知道如何做到这一点,请在这里评论,我很乐意测试它.谢谢.


小智 6

在IE中将光标移动到某个位置,这段代码就足够了:

var range = elt.createTextRange();
range.move('character', pos);
range.select();
Run Code Online (Sandbox Code Playgroud)


小智 6

在将文本插入textarea之前设置焦点?

$("#comments").focus();
$("#comments").val(comments);
Run Code Online (Sandbox Code Playgroud)


小智 5

这适用于我的铬

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

显然你需要延迟一微秒或更长时间,因为通常用户通过点击文本字段中的某个位置(或通过点击标签)来关注文本字段,因此你必须等到位置是由用户设置单击,然后更改它.