将光标放在JavaScript文本框的末尾 [英] Putting cursor at end of textbox in javascript
问题描述
我有一个文本框,当我把焦点放在焦点上时,我希望光标到达文本框的末尾。
继续出现的解决方案只是
p> this.value = this.value
我用一个简单的方法onclick来试试这个:
function InputClicked(element){
element.className =inputfocused;
element.value = element.value;
}
但是这个跟这个怪有关,它好像跳到最后然后跳转到文本框的开始处。
您必须关注元素并设置插入符号位置
这 JSFiddle 向您展示了它的工作原理。在这个例子中,为了简单起见,jQuery已经被使用了,但如果需要的话,它可以被完全省略。 setSelectionRange
函数是一个DOM函数。
一般来说,它是这样做的:
input.focus();
input.setSelectionRange(inputValueLength,inputValueLength);
获取输入及其值长度可以使用DOM功能或使用库函数获得(如在jQuery中) 。
我们是否需要输入值长度?
我没有在其他浏览器中测试过,但在Chrome中运行它允许设置一个大于实际的位置,并且脱字符将位于最后。例如:
input.setSelectionRange(1000,1000);
将按预期工作(假设您的文本短于1000个字符)。
注意:此功能在IE8及更低版本中不受支持。所有最新版本的大多数浏览器都支持它。对于老版本的IE浏览器,请使用文本范围。
I have a textbox that when I put on focus I want the cursor to goto the end of the textbox.
The solution that keeps coming up is just
this.value = this.value
I have tried this with a simple method onclick:
function InputClicked(element) {
element.className = "inputfocused";
element.value = element.value;
}
but the strange this with this, it seems to goto the end and then jump to the start of the textbox.
You have to focus element AND set caret position
This JSFiddle shows you how it works. jQuery has been used for simplicity in this example, but it can be completely omitted if one desires so. setSelectionRange
function is a DOM function anyway.
In general it does this:
input.focus();
input.setSelectionRange(inputValueLength, inputValueLength);
Obtaining input and its value length can be obtained using DOM functionality or using library functions (as in jQuery).
Do we need input value length?
I haven't tested in other browsers but running in Chrome it allows to set a larger than actual position and caret will be positioned at the end. So something like:
input.setSelectionRange(1000,1000);
will work as expected (provided your text is shorter than 1000 characters. :)
Note: This function isn't supported in IE8 and older. All latest versions of most used browsers support it. For older versions of IE resort to text ranges.
这篇关于将光标放在JavaScript文本框的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!