首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jQuery设置光标在文本区域的位置

jQuery设置光标在文本区域的位置
EN

Stack Overflow用户
提问于 2009-01-31 16:39:11
回答 15查看 363.9K关注 0票数 447

如何使用jQuery设置文本字段中的光标位置?我有一个包含内容的文本字段,当用户聚焦于该字段时,我希望用户的光标定位在特定的偏移量上。代码看起来应该是这样的:

代码语言:javascript
运行
复制
$('#input').focus(function() {
  $(this).setCursorPosition(4);
});

这个setCursorPosition函数的实现是什么样子的?如果您有一个包含内容abcdefg的文本字段,则此调用将导致光标被定位为以下位置:abcd**x**efg。

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

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

代码语言:javascript
运行
复制
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);
EN

回答 15

Stack Overflow用户

回答已采纳

发布于 2009-01-31 16:56:36

我有两个职能:

代码语言:javascript
运行
复制
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);
}

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

代码语言:javascript
运行
复制
setCaretToPos(document.getElementById("YOURINPUT"), 4);

使用textareainput进行实例化,显示来自jQuery的用法:

代码语言:javascript
运行
复制
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);
});
代码语言:javascript
运行
复制
<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,火狐,IE11,甚至IE8都在进行测试和工作(参见最后的这里;堆栈片段不支持IE8)。

票数 263
EN

Stack Overflow用户

发布于 2009-05-08 18:17:32

下面是一个jQuery解决方案:

代码语言:javascript
运行
复制
$.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();
        }
    });
};

有了这个,你就可以

代码语言:javascript
运行
复制
$('#elem').selectRange(3,5); // select a range of text
$('#elem').selectRange(3); // set cursor position
票数 301
EN

Stack Overflow用户

发布于 2011-08-24 19:02:59

我找到了一个对我有用的解决方案:

代码语言:javascript
运行
复制
$.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;
}

现在,您可以通过调用以下命令将焦点移到任何元素的末尾:

代码语言:javascript
运行
复制
$(element).focusEnd();

或者你指定职位。

代码语言:javascript
运行
复制
$(element).setCursorPosition(3); // This will focus on the third character.
票数 24
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/499126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档