什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?


当前回答

有一种简单的方法可以让它在大多数浏览器中工作。

this.selectionStart = this.selectionEnd = this.value.length;

然而,由于一些浏览器的特性,一个更全面的答案是这样的

setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);

使用jQuery(设置监听器,否则不需要)

$ (' # el) .focus(函数(){ Var that = this; () {setTimeout(函数。selectionStart = that。selectionEnd = 10000;},0); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <input id='el' type='text' value='put cursor at end'>

使用Vanilla JS(从答案中借用addEvent函数)

//基本的跨浏览器addEvent 函数addEvent(elem,事件,fn){ 如果(elem.addEventListener) { 初步的。addEventListener(事件,fn, false); 其他}{ 初步的。attachEvent(“on”+事件, 函数(){返回(fn。调用(elem window.event));}); }} var element = document.getElementById('el'); addEvent(元素、“焦点”函数(){ Var that = this; () {setTimeout(函数。selectionStart = that。selectionEnd = 10000;},0); }); <input id='el' type='text' value='put cursor at end'>


怪癖

Chrome有一个奇怪的怪癖,焦点事件在光标移动到字段之前被触发;这打乱了我简单的解决方案。有两个选项可以解决这个问题:

您可以添加一个0毫秒的超时(将操作延迟到堆栈清空为止) 您可以将事件从焦点更改为鼠标悬停。这对用户来说是相当烦人的,除非你仍然保持焦点。这两种选择我都不太喜欢。

此外,@vladkras指出,一些旧版本的Opera在有空格时,会错误地计算长度。为此,你可以使用一个巨大的数字,应该大于你的字符串。

其他回答

设置光标时,点击文本区域的文本结束… 这段代码的变体是…也工作!Firefox, IE, Safari, Chrome..

在服务器端代码中:

txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")

在Javascript中:

function sendCursorToEnd(obj) {
    var value =  $(obj).val(); //store the value of the element
    var message = "";
    if (value != "") {
        message = value + "\n";
     };
    $(obj).focus().val(message);
    $(obj).unbind();
 }

下面是我的答案的jsFiddle演示。演示使用CoffeeScript,但如果需要,可以将其转换为纯JavaScript。

JavaScript中重要的部分是:

var endIndex = textField.value.length;
if (textField.setSelectionRange) {
   textField.setSelectionRange(endIndex, endIndex);
}

我把这个答案贴出来是因为我已经为有同样问题的其他人写过了。这个答案不像上面的答案那样涵盖那么多的边缘情况,但它适合我,并且有一个jsFiddle演示可以玩。

下面是来自jsFiddle的代码,所以即使jsFiddle消失了,这个答案也会被保留:

moveCursorToEnd = (textField) ->
  endIndex = textField.value.length
  if textField.setSelectionRange
    textField.setSelectionRange(endIndex, endIndex)

jQuery ->
  $('.that-field').on 'click', ->
    moveCursorToEnd(this)
<div class="field">
    <label for="pressure">Blood pressure</label>:
    <input class="that-field" type="text" name="pressure" id="pressure" value="24">
</div>
<p>
    Try clicking in the text field. The cursor will always jump to the end.
</p>
body {
    margin: 1em;
}

.field {
    margin-bottom: 1em;
}

我从这里得到了最好的答案,并创建了一个在Chrome中工作良好的功能。

您需要将逻辑封装在一个超时中,因为您必须等待焦点完成后才能访问所选内容 要将光标放在末尾,选择起始点需要放在末尾 为了滚动到输入字段的末尾,scrollLeft需要匹配scrollWidth

/** * Upon focus, set the cursor to the end of the text input * @param {HTMLInputElement} inputEl - An HTML <input> element */ const setFocusEnd = (inputEl) => { setTimeout(() => { const { scrollWidth, value: { length } } = inputEl; inputEl.setSelectionRange(length, length); inputEl.scrollLeft = scrollWidth; }, 0); }; document .querySelector('input') .addEventListener('focus', (e) => setFocusEnd(e.target)); html, body { width: 100%; height: 100%; margin: 0; } body { display: flex; flex-direction: column; justify-content: center; align-items: center; } input:focus { background-color: hsla(240, 100%, 95%, 1.0); } <input type="text" placeholder="Search..." value="This is some really, really long text">

我喜欢接受的答案很多,但它停止工作在Chrome。在Chrome浏览器中,光标要走到最后,需要改变输入值。解决方法如下:

<input id="search" type="text" value="mycurrtext" size="30" 
   onfocus="var value = this.value; this.value = null; this.value = value;" name="search"/>

检查这个解决方案!

//fn setCurPosition $.fn.setCurPosition = function(pos) { this.focus(); 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; }; // USAGE - Set Cursor ends $('#str1').setCurPosition($('#str1').val().length); // USAGE - Set Cursor at 7 position // $('#str2').setCurPosition(7); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>Set cursor at any position</p> <p><input type="text" id="str1" value="my string here" /></p> <p><input type="text" id="str2" value="my string here" /></p>