使用JavaScript将光标放在文本输入元素中的文本末尾

Pea*_*nut 291 javascript

通过JavaScript将光标放在输入文本元素中文本末尾的最佳方法(我假设最简单的方法)是什么?在焦点设置为元素之后?

Gar*_*ary 177

有一种简单的方法可以让它在大多数浏览器中运行.

this.selectionStart = this.selectionEnd = this.value.length;
Run Code Online (Sandbox Code Playgroud)

但是,由于一些浏览器的怪癖,更具包容性的答案看起来更像这样

setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
Run Code Online (Sandbox Code Playgroud)

使用jQuery (设置监听器,但不是必须的)

$('#el').focus(function(){
  var that = this;
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='el' type='text' value='put cursor at end'>
Run Code Online (Sandbox Code Playgroud)

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

// Basic cross browser addEvent
function addEvent(elem, event, fn){
if(elem.addEventListener){
  elem.addEventListener(event, fn, false);
}else{
  elem.attachEvent("on" + event,
  function(){ return(fn.call(elem, window.event)); });
}}
var element = document.getElementById('el');

addEvent(element,'focus',function(){
  var that = this;
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
Run Code Online (Sandbox Code Playgroud)
<input id='el' type='text' value='put cursor at end'>
Run Code Online (Sandbox Code Playgroud)


怪癖

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

  1. 您可以添加0毫秒的超时(推迟操作直到堆栈清除)
  2. 您可以将事件从更改focusmouseup.这对用户来说非常烦人,除非你仍然跟踪焦点.我并不是真的爱上这两种选择.

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

  • 这是一个很好的解决方案,而不是观察(kludge),代码更少,并且比这里讨论的替代方案更容易理解.谢谢. (4认同)
  • 在Chrome 24.0.1312.57,IE 9.0.8112和Firefox 18.0.2中为我工作 (2认同)

Mik*_*row 170

我在IE中遇到了同样的问题(在通过RJS /原型设置焦点之后).当已经存在该字段的值时,Firefox已经将光标留在最后.IE正在强制光标到文本的开头.

我得到的解决方案如下:

<input id="search" type="text" value="mycurrtext" size="30" 
       onfocus="this.value = this.value;" name="search"/>
Run Code Online (Sandbox Code Playgroud)

这适用于IE7和FF3

  • 立即在Chrome中使用(9.0.597.98) (19认同)
  • 现在这[在IE9中不起作用](http://jsfiddle.net/Town/eChds/) - 光标跳转到字段的开头. (6认同)
  • 在FF 8中也不起作用.来自chenosaurus的解决方案似乎有效. (6认同)
  • textarea 将是什么? (4认同)
  • 在Chrome 24.0.1312.57,IE 9.0.8112中为我工作,但不是Firefox 18.0.2 (3认同)
  • 不再适用于 Chrome 81。/sf/answers/3426294791/ 确实有效 (2认同)

che*_*rus 149

试试这个,它对我有用:

//input is the input element

input.focus(); //sets focus to element
var val = this.input.value; //store the value of the element
this.input.value = ''; //clear the value of the element
this.input.value = val; //set that value back.  
Run Code Online (Sandbox Code Playgroud)

要使光标移动到最后,输入必须首先具有焦点,然后当值改变时,它将转到结尾.如果将.value设置为相同,则不会更改chrome.

  • 在设置值之前设置焦点是使其在Chrome中运行的关键. (14认同)
  • 为什么在第2,3和4行的输入前放置`this`?我们已经知道`input`是输入元素.使用`this`似乎是多余的.否则就是好方法! (7认同)
  • @Tareq他们不一样.这个技巧比接受的答案要好得多. (3认同)
  • 更简单:`$ input.focus().val($ input.val());` (3认同)
  • 这就像onfocus ="this.value = this.value; (2认同)

tee*_*yay 97

在对此进行了一些黑客攻击后,我发现最好的方法是使用该setSelectionRange功能,如果浏览器支持它; 如果没有,请回复使用Mike Berrow的答案中的方法(即将值替换为自身).

scrollTop如果我们处于可垂直滚动状态,我也会设置很高的值textarea.(使用任意高值似乎比$(this).height()Firefox和Chrome 更可靠.)

我已经把它作为一个jQuery插件.(如果你没有使用jQuery,我相信你仍然可以轻松地获得要点.)

我已经在IE6,IE7,IE8,Firefox 3.5.5,谷歌Chrome 3.0,Safari 4.0.4,Opera 10.00中进行了测试.

它在jquery.com上可用作PutCursorAtEnd插件.为方便起见,1.0版的代码如下:

// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea

// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
    jQuery.fn.putCursorAtEnd = function()
    {
    return this.each(function()
    {
        $(this).focus()

        // If this function exists...
        if (this.setSelectionRange)
        {
        // ... then use it
        // (Doesn't work in IE)

        // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
        var len = $(this).val().length * 2;
        this.setSelectionRange(len, len);
        }
        else
        {
        // ... otherwise replace the contents with itself
        // (Doesn't work in Google Chrome)
        $(this).val($(this).val());
        }

        // Scroll to the bottom, in case we're in a tall textarea
        // (Necessary for Firefox and Google Chrome)
        this.scrollTop = 999999;
    });
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

  • 为什么计算长度?为什么不只是this.setSelectionRange(9999,9999),如果你打算过冲呢? (4认同)

小智 20

<script type="text/javascript">  
    function SetEnd(txt) {  
      if (txt.createTextRange) {  
       //IE  
       var FieldRange = txt.createTextRange();  
       FieldRange.moveStart('character', txt.value.length);  
       FieldRange.collapse();  
       FieldRange.select();  
       }  
      else {  
       //Firefox and Opera  
       txt.focus();  
       var length = txt.value.length;  
       txt.setSelectionRange(length, length);  
      }  
    }   
</script>  
Run Code Online (Sandbox Code Playgroud)

这个功能适用于IE9,Firefox 6.x和Opera 11.x.

  • 出于某种原因,流行的答案对我不起作用.这很完美. (3认同)

Hej*_*ner 16

我在chrome中取得了相当大的成功

$("input.focus").focus(function () {
    var val = this.value,
        $this = $(this);
    $this.val("");

    setTimeout(function () {
        $this.val(val);
    }, 1);
});
Run Code Online (Sandbox Code Playgroud)

快速破解:

它将每个输入字段与类焦点放在一起,然后将输入字段的旧值存储在变量中,之后将空字符串应用于输入字段.

然后它等待1毫秒并再次输入旧值.

  • @ zac1987可能不是这种情况,因为php会渲染html,html会被加载到客户端然后js会运行.您有可能不等待文档就绪事件. (3认同)

see*_*con 11

el.setSelectionRange(-1, -1);

https://codesandbox.io/s/peaceful-bash-x2mti

此方法在一次调用中更新 HTMLInputElement.selectionStart、selectionEnd 和 selectionDirection 属性。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

在其他js方法中-1通常意味着(到)最后一个字符。这也是这种情况,但我在文档中找不到明确提及这种行为。


Wen*_* Du 10

const end = input.value.length
input.setSelectionRange(end, end)
//  scroll to the bottom if a textarea has long text
input.focus()
Run Code Online (Sandbox Code Playgroud)


Kis*_*ton 9

尝试一下这个可以与 Vanilla JavaScript 一起使用。

<input type="text" id="yourId" onfocus="let value = this.value; this.value = null; this.value=value" name="nameYouWant" class="yourClass" value="yourValue" placeholder="yourPlaceholder...">
Run Code Online (Sandbox Code Playgroud)

在 Js 中

document.getElementById("yourId").focus()
Run Code Online (Sandbox Code Playgroud)


Aru*_*E S 7

简单.编辑或更改值时,首先放置焦点然后设置值.

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


小智 6

仍然需要中间变量,(参见var val =)否则游标表现很奇怪,我们最后需要它.

<body onload="document.getElementById('userinput').focus();">
<form>
<input id="userinput" onfocus="var val=this.value; this.value=''; this.value= val;"
         class=large type="text" size="10" maxlength="50" value="beans" name="myinput">
</form>
</body>
Run Code Online (Sandbox Code Playgroud)


小智 5

对于所有情况的所有浏览器:

function moveCursorToEnd(el) {
    window.setTimeout(function () {
            if (typeof el.selectionStart == "number") {
            el.selectionStart = el.selectionEnd = el.value.length;
        } else if (typeof el.createTextRange != "undefined") {
            var range = el.createTextRange();
            range.collapse(false);
            range.select();
        }
    }, 1);
}
Run Code Online (Sandbox Code Playgroud)

如果需要从onFocus事件处理程序移动光标,则需要超时


Kon*_*d G 5

我非常喜欢接受的答案,但它在 Chrome 中停止工作。在 Chrome 中,为了让光标移动到最后,需要更改输入值。解决方法如下:

<input id="search" type="text" value="mycurrtext" size="30" 
   onfocus="var value = this.value; this.value = null; this.value = value;" name="search"/>
Run Code Online (Sandbox Code Playgroud)


And*_*atz 5

这是2019年,上面的方法都不适合我,但是这个方法确实有用,取自https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/

function moveCursorToEnd(id) {
  var el = document.getElementById(id) 
  el.focus()
  if (typeof el.selectionStart == "number") {
      el.selectionStart = el.selectionEnd = el.value.length;
  } else if (typeof el.createTextRange != "undefined") {           
      var range = el.createTextRange();
      range.collapse(false);
      range.select();
  }
}
Run Code Online (Sandbox Code Playgroud)
<input id="myinput" type="text" />
<a href="#" onclick="moveCursorToEnd('myinput')">Move cursor to end</a>
Run Code Online (Sandbox Code Playgroud)


Ha *_* Ja 5

document.querySelector('input').addEventListener('focus', e => {
  const { value } = e.target;
  e.target.setSelectionRange(value.length, value.length);
});
Run Code Online (Sandbox Code Playgroud)
<input value="my text" />
Run Code Online (Sandbox Code Playgroud)