使用 JavaScript 将光标放在文本输入元素中文本的末尾
2022-08-29 23:36:51
在焦点设置为元素之后,通过JavaScript将光标放在输入文本元素中文本末尾的最佳方法(我推测是最简单的方法)是什么?
在焦点设置为元素之后,通过JavaScript将光标放在输入文本元素中文本末尾的最佳方法(我推测是最简单的方法)是什么?
有一种简单的方法可以让它在大多数浏览器中工作。
this.selectionStart = this.selectionEnd = this.value.length;
但是,由于一些浏览器的*怪癖,更具包容性的答案看起来更像这样
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
使用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'>
使用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'>
Chrome有一个奇怪的怪癖,即焦点事件在光标移动到字段之前触发;这搞砸了我的简单解决方案。解决此问题的两个选项:
focus
mouseup
此外,@vladkras指出,一些旧版本的Opera在有空格时会错误地计算长度。为此,您可以使用一个应该大于字符串的大数字。
试试这个,它对我有用:
//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.
要将光标移动到末尾,输入必须首先具有焦点,然后当值更改时,它将转到末尾。如果将 .value 设置为相同,则在 chrome 中它不会更改。