在 html 中,输入字段用于获取用户的输入。有时,我们需要在输入中获取字符串或长文本消息。在这些场景中,用户可能需要转到输入字段的末尾来添加更多内容或消息。因此,我们应该设置一些东西,以便用户可以单击按钮,可以转到输入字段的末尾。在本教程中,我们将学习使用 javascript 将光标位置放置在输入字段中文本的末尾。
使用 setselectionrange() 方法setselectionrange() 方法用于选择输入字段中的文本。需要两个参数来开始和结束选择。我们可以使用 setselectionrange() 方法选择最后一个字符,将光标置于文本末尾。
语法用户可以按照以下语法使用setselectionrange()方法将光标置于文本末尾。
input.setselectionrange(len, len);
在上面的语法中,输入是我们在 javascript 中访问的 html 元素。“len”是输入值的长度。
示例在下面的示例中,我们创建了输入字段和按钮。当用户单击该按钮时,它会执行 moveatend() 函数。
在 javascript 中,我们定义了 moveatend() 函数,该函数访问“名称”输入字段。之后,它使用 focus() 方法将焦点设置在输入字段上。之后,我们通过将输入值的长度作为两个参数传递来使用 setselectionrange() 方法。在输出中,用户可以单击该按钮并观察它将光标位置设置在文本末尾。
<html> <body> <h3> using the <i> setselectionrange() method </i> to move the cursor at the end of the input field in javascript </h3> <input type = text id = name value = shubham> <button onclick = moveatend()> move cursor at end </button> <script> let output = document.getelementbyid(output); function moveatend() { let name = document.getelementbyid(name); name.focus(); name.setselectionrange(name.value.length, name.value.length); } </script></html>
使用selectionstart和selectionend属性“selectionstart”和“selectionend”css 属性用于选择输入字段中的输入值。 “selectionstart”采用从开始选择的位置开始的索引值,“selectionend”采用我们需要结束文本选择的索引值。
在这里,我们可以将“selectionstart”和“selectionend”属性的值设置为等于文本长度,以将光标置于文本末尾。
语法用户可以按照以下语法使用“selectionstart”和“selectionend”属性将光标置于文本末尾。
input.selectionstart = len;input.selectionend = len;
在上面的语法中,input是一个html元素,‘len’是它的值的长度。
示例与第一个示例一样,我们在下面的示例中创建了输入字段。在 moveatend() 函数中,我们将“selectionstart”和“selectionend”属性的值设置为等于“name”输入字段的文本长度。
<html> <body> <h3> using the <i> selectionstart and selectionend properties </i> to move the cursor at the end of the input field in javascript </h3> <input type = text id = name value = shubham> <button onclick = moveatend()> move cursor at end </button> <script> let output = document.getelementbyid(output); function moveatend() { let name = document.getelementbyid(name); name.focus(); name.selectionstart = name.value.length; name.selectionend = name.value.length; } </script></html>
结论我们学习了两种将光标置于输入字段中文本值末尾的方法。在第一种方法中,我们使用了 setselectionrange() 方法;在第二种方法中,我们使用了“selectionstart”和“selectionend”属性。但是,这两种方法几乎相同,setselectionrange() 方法将“selectionstart”和“selection”结束值作为参数。
以上就是如何使用 javascript 将光标位置放置在文本输入字段中的文本末尾?的详细内容。
