使用jQuery在输入的文本中设置光标

Set cursor within text of input using jQuery

本文关键字:置光标 文本 jQuery 输入 使用      更新时间:2023-09-26

使用此主题:jQuery设置文本区域中的光标位置

我写了这个代码,但它不起作用:

<input id="myTextInput" type="text" value="some text2">
<input type="button" value="set mouse" id="btn" />

和:

$(document).ready(function () {
    $('#btn').on('click', function () {
        var inp = $('#myTextInput');        
        var pos = 3;
        inp.focus();
        if (inp.setSelectionRange) {
            inp.setSelectionRange(pos, pos);
        } else if (inp.createTextRange) {
            var range = inp.createTextRange();
            range.collapse(true);
            if (pos < 0) {
                pos = $(this).val().length + pos;
            }
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    });
});

演示

我的错误在哪里?感谢

您的错误是选择了jQuery对象而不是DOM元素:用var inp = $('#myTextInput')[0];替换var inp = $('#myTextInput');

JSFIDDLE


然而,我建议使用这个答案中的插件,因为代码看起来更干净:

$.fn.selectRange = function(start, end) {
  return this.each(function() {
    if (this.setSelectionRange) {
      this.focus();
      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();
    }
  });
};
$(document).ready(function() {
  $('#btn').on('click', function() {
    var pos = 7;
    $('#myTextInput').focus().selectRange(pos, pos);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextInput" type="text" value="some text2">
<input type="button" value="set mouse" id="btn" />

要使用setSelectionRangecreateTextRange,需要DOM元素而不是JQuery对象。使用.get(0)进行检索。

var inp = $('#myTextInput');
inp.focus();
inp = inp.get(0);

http://jsfiddle.net/qeanb8gk/1/