在将焦点设置到元素之后,通过JavaScript将光标放在输入文本元素的文本末尾,最好的方法(我认为是最简单的方法)是什么?
发布于 2009-04-10 00:16:15
我在IE中也遇到过同样的问题(在通过RJS/prototype设置焦点之后)。当字段已经有一个值时,Firefox已经将光标留在了结尾处。IE将光标强制移动到文本的开头。
我得出的解决方案如下:
<input id="search" type="text" value="mycurrtext" size="30"
onfocus="this.value = this.value;" name="search"/>这在IE7和FF3中都有效
发布于 2012-05-14 08:46:52
有一种简单的方法可以让它在大多数浏览器中运行。
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事件;这会把我的简单解决方案搞砸。解决此问题的两个选项:
您可以添加0毫秒的超时(到defer the operation until the stack is clear)
focus更改为mouseup。这对用户来说是相当烦人的,除非你仍然跟踪焦点。我并不是真的喜欢这两个选项。此外,@vladkras指出,当Opera有空格时,一些旧版本的Opera会错误地计算长度。为此,您可以使用一个应该大于字符串的大数字。
发布于 2010-02-27 09:39:51
试试这个,它对我很有效:
//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中不会改变。
https://stackoverflow.com/questions/511088
复制相似问题