将光标放在JavaScript文本框的末尾

编程入门 行业动态 更新时间:2024-10-26 06:31:33
本文介绍了将光标放在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文本框的末尾

本文发布于:2023-11-09 16:00:11,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:放在   末尾   光标   文本框   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!