gpt4 book ai didi

javascript - 我怎样才能关注文本区域值的结尾?

转载 作者:行者123 更新时间:2023-11-30 11:15:40 25 4
gpt4 key购买 nike

这是我的代码:

$('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" />

如何关注textarea值的结尾?


如您所见,目前当您单击按钮时,您将关注文本区域,但在其值的开头。我想要做的就是专注于该 textarea 值的末尾。

最佳答案

您可以使用setSelectionRange(start,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" />

关于javascript - 我怎样才能关注文本区域值的结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51683503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com