jQuery 将光标放在文本输入值的末尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17780756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
put cursor at end of text input's value
提问by Django Johnson
So, currently I have a text-input-field with a value that is also autofocused.
所以,目前我有一个文本输入字段,其值也是自动聚焦的。
On page load, the value is selected / highlighted. Is there a way I can put the cursor at the end of the value text instead of highlighting it in javascript or CSS?
在页面加载时,该值被选中/突出显示。有没有办法可以将光标放在值文本的末尾而不是在 javascript 或 CSS 中突出显示它?
Here is a js fiddle where the autofocused text's value is highlighted: http://jsfiddle.net/TaGL5/
这是一个 js 小提琴,其中突出显示了自动聚焦文本的值:http: //jsfiddle.net/TaGL5/
Here is the HTML code: <input type="text" value="value text" autofocus />
这是 HTML 代码: <input type="text" value="value text" autofocus />
回答by Harsha Venkatram
This works for me
这对我有用
<input type="text" autofocus value="value text" onfocus="this.value = this.value;"/>
回答by J_z
Upgrade to @harsha's answer
升级到@harsha 的答案
I found that to make solution work with Firefox, we need temporary reset value to "not-equal of value", then set it back
我发现要使解决方案与 Firefox 一起工作,我们需要临时将值重置为“不等于值”,然后将其设置回
<input type="text" autofocus value="value text" onfocus="var temp_value=this.value; this.value=''; this.value=temp_value" />
回答by Ishan Jain
Use Jquery for this:
为此使用 Jquery:
$(function() {
var input = $("#txt1");
var len = input.val().length;
input[0].focus();
input[0].setSelectionRange(len, len);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="txt1" value="Lorem" style="width:400px;" />
But some browsers don't support enter code here
property, in which case use this:
但是有些浏览器不支持enter code here
属性,在这种情况下使用这个:
$(document).ready(function(){
$("#search").focus(function(){
if (this.setSelectionRange)
{
var len = $(this).val().length;
this.setSelectionRange(len, len);
}
else
{
$(this).val($(this).val());
}
});
$("#search").focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="search" type="text" value="mycurrtext" size="30" name="search" />
This question already exist on stackoverflow:
这个问题在stackoverflow上已经存在:
回答by Obaidul Haque
Use this, its nice work for me...
使用这个,它对我来说很好...
<input type="text" name="txt" value="value text" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);">
OR add this line to your input element
或将此行添加到您的输入元素
onfocus="this.setSelectionRange(this.value.length,this.value.length);"