简体   繁体   English

我怎样才能专注于textarea价值的终结?

[英]How can I focus on the end of textarea value?

Here is my code: 这是我的代码:

 $('input').on('click', function(){ $('textarea').focus(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea>this is a test</textarea> <br /> <input type="button" value="focus" /> 

How can I focus on the end of textarea value? 我怎样才能专注于textarea价值的终结?


As you can see, currently when you click on the button, you will be focused on the textarea, but at the beginning of its value. 正如您所看到的,当前单击按钮时,您将专注于textarea,但在其值的开头。 All I'm trying to do is focusing at the end of that textarea value. 我所要做的就是专注于textarea值的结尾。

You can use setSelectionRange(start,end) , the arguments are the starting point and the end point of the selection it is setting. 您可以使用setSelectionRange(start,end) ,参数是它所设置的选择的起点和终点。 If you set both to the last index of the value string, the cursor will be at the end. 如果将两者都设置为值字符串的最后一个索引,则光标将位于结尾。

 $('input').on('click', function(){ let l=$("textarea").val().length $('textarea').focus() $('textarea')[0].setSelectionRange(l,l); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea>this is a test</textarea> <br /> <input type="button" value="focus" /> 

You can try the following way: 您可以尝试以下方式:

 $('input').on('click', function(){ var preVal = $('#txtArea').val(); $('#txtArea').val(''); $('#txtArea').focus().val(preVal); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="txtArea">this is a test</textarea> <br /> <input type="button" value="focus" /> 

One way to go about it is as follows: 其中一种方法如下:

  1. Capture the previous text. 捕获以前的文本。
  2. focus. 焦点。
  3. append ' ' to the previous value. ' '附加到前一个值。

 $('input').on('click', function(){ var text = $('textarea').val(); $('textarea').focus(); $('textarea').val(text + ' '); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea>this is a test</textarea> <br /> <input type="button" value="focus" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM