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

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

setCursorPosition函数的实现会是什么样子?如果您有一个内容为ABCDEFG的文本字段,此调用将导致光标定位如下:abcd**|**EFG.

Java有一个类似的函数,setCaretPosition.javascript有类似的方法吗?

Update: I modified CMS's code to work with jQuery as follows:

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);

推荐答案

我有两个功能:

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);
}

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

setCaretToPos(document.getElementById("YOURINPUT"), 4);

textareainput为例,展示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);
});
<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>

截至2016年,他们已经在Chrome、Firefox、IE11甚至IE8上进行了测试和工作(见最后here条;堆栈片段不支持IE8).

Javascript相关问答推荐

我的YouTube视频没有以html形式显示,以获取免费加密信号

JavaScript文本区域阻止KeyDown/KeyUp事件本身上的Alt GR +键组合

如何修复内容安全策略指令脚本-SRC自身错误?

Vue:ref不会创建react 性属性

react/redux中的formData在expressjs中返回未定义的req.params.id

类型自定义lazy Promise. all

D3 Scale在v6中工作,但在v7中不工作

单击ImageListItemBar的IconButton后,在Material—UI对话框中显示图像

处理时间和字符串时MySQL表中显示的日期无效

如何从调整大小/zoom 的SVG路径定义新的d属性?""

无法读取未定义错误的属性路径名''

对路由DOM嵌套路由作出react

基于props 类型的不同props ,根据来自接口的值扩展类型

使用VUE和SCSS的数字滚动动画(&;内容生成)

让chart.js饼图中的一个切片变厚?

是否可以将异步调用与useState(UnctionName)一起使用

是否可以在不更改组件标识的情况下换出Reaction组件定义(以维护状态/引用等)?如果是这样的话,是如何做到的呢?

我的NavLink活动类在REACT-ROUTER-V6中出现问题

如何在移动设备中使用JAVASSCRIPT移除点击时的焦点/悬停状态

从异步操作返回对象