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

本文翻译自:Use JavaScript to place cursor at end of text in text input element

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


#1楼

参考:https://stackoom.com/question/28xM/使用JavaScript将光标放在文本输入元素中的文本末尾


#2楼

好吧,我只是使用:

$("#myElement").val($("#myElement").val());

#3楼

There's a simple way to get it working in most browsers. 有一种简单的方法可以使它在大多数浏览器中运行。

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

However, due to the *quirks of a few browsers, a more inclusive answer looks more like this 但是,由于一些浏览器的怪癖,一个更具包容性的答案看起来像这样

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

Using jQuery (to set the listener, but it's not necessary otherwise) 使用jQuery (设置侦听器,但没有必要)

 $('#el').focus(function(){ var that = this; setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0); }); 
 <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'> 

Using Vanilla JS (borrowing addEvent function from this answer ) 使用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); }); 
 <input id='el' type='text' value='put cursor at end'> 


Quirks 怪癖

Chrome has an odd quirk where the focus event fires before the cursor is moved into the field; Chrome有一个奇怪的怪癖,即在光标移到该字段之前触发焦点事件。 which screws my simple solution up. 这使我的简单解决方案搞砸了。 Two options to fix this: 解决此问题的两种方法:

  1. You can add a timeout of 0 ms (to defer the operation until the stack is clear ) 您可以添加0毫秒的超时(以将操作推迟到清除堆栈为止
  2. You can change the event from focus to mouseup . 您可以将事件从focus更改为mouseup This would be pretty annoying for the user unless you still kept track of focus. 除非您仍然关注焦点,否则这对于用户而言将是非常烦人的。 I'm not really in love with either of these options. 我对这些选项都不是很喜欢。

Also, @vladkras pointed out that some older versions of Opera incorrectly calculate the length when it has spaces. 另外,@ vladkras指出,某些较旧版本的Opera在有空格时会错误地计算长度。 For this you can use a huge number that should be larger than your string. 为此,您可以使用巨大的数字,该数字应大于字符串。


#4楼

Here's a jsFiddle demo of my answer. 这是我的答案的jsFiddle演示 The demo uses CoffeeScript, but you can convert it to plain JavaScript if you need to. 该演示使用CoffeeScript,但是您可以根据需要将其转换为纯JavaScript

The important part, in JavaScript: JavaScript中的重要部分:

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

I'm posting this answer because I already wrote it for someone else who had the same question. 我发布此答案是因为我已经为其他有相同问题的人写过答案。 This answer doesn't cover as many edge cases as the top answers here, but it works for me, and has a jsFiddle demo you can play with. 这个答案不像这里的最高答案那样涵盖很多边缘情况,但是它对我有用,并且有一个jsFiddle演示可以使用。

Here is the code from the jsFiddle, so this answer is preserved even if the jsFiddle disappears: 这是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;
}

#5楼

After hacking around with this a bit, I found the best way was to use the setSelectionRange function if the browser supports it; 经过一番研究之后,我发现最好的方法是在浏览器支持的情况下使用setSelectionRange函数。 if not, revert to using the method in Mike Berrow's answer (ie replace the value with itself). 如果不是,请恢复使用Mike Berrow答案中的方法(即用自身替换值)。

I'm also setting scrollTop to a high value in case we're in a vertically-scrollable textarea . 如果我们在垂直可滚动的textarea我也将scrollTop设置为较高的值。 (Using an arbitrary high value seems more reliable than $(this).height() in Firefox and Chrome.) (在Firefox和Chrome中,使用任意高值似乎比$(this).height()更可靠。)

I've made it is as a jQuery plugin. 我已经将它作为jQuery插件使用。 (If you're not using jQuery I trust you can still get the gist easily enough.) (如果您不使用jQuery,我相信您仍然可以很容易地获得要点。)

I've tested in IE6, IE7, IE8, Firefox 3.5.5, Google Chrome 3.0, Safari 4.0.4, Opera 10.00. 我已经在IE6,IE7,IE8,Firefox 3.5.5,Google Chrome 3.0,Safari 4.0.4,Opera 10.00中进行了测试。

It's available on jquery.com as the PutCursorAtEnd plugin . 它可以作为PutCursorAtEnd插件jquery.com上使用 For your convenience, the code for release 1.0 is as follows: 为了您的方便,版本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);

#6楼

Try this, it has worked for me: 试试这个,它对我有用:

//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.  

For the cursor to be move to the end, the input has to have focus first, then when the value is changed it will goto the end. 为了使光标移到末尾,输入必须首先具有焦点,然后在更改值时将其移到末尾。 If you set .value to the same, it won't change in chrome. 如果将.value设置为相同,则chrome不会更改。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值