JavaScript 如何将光标位置置于文本输入字段的末尾
在本文中,我们将学习如何使用JavaScript将光标置于文本输入元素末尾的方法。
首先,我们将创建一个文本输入框,其中会有一些值,并且有一个按钮用于将光标放置在末尾。我们可以使用不同的JavaScript函数将光标放置在文本输入元素的末尾。
方法: 使用的JavaScript函数包括:
- HTMLInputElement.setSelectionRange() :HTMLInputElement.setSelectionRange()是一种将当前文本选择的起始和结束位置设置为或元素的方法。
- Element.createTextRange() :它为我们提供了输入表单中的选定文本范围。光标也被称为文本光标,它是屏幕上用于指示文本插入位置的指示器。
- TextRange.collapse() :它帮助将光标移动到当前范围的开头或末尾。
- TextRange.moveEnd() :它帮助将范围的末尾移动指定的单位数。
- TextRange.moveStart() :它将范围的起始位置移动指定的单位数。
示例: 这个示例展示了上述解释的方法。
<!DOCTYPE html>
<html>
<body>
<center>
<h1>Put Cursor at End of Input</h1>
<!-- Creating an Input Text Box and
the button to move cursor at the
end of the text-->
<input id="idText" type="text" size="70"
value="Cursor at the End">
<button onclick="PosEnd(idText);">
Put Cursor at end of Text
</button>
</center>
<script>
/* Creating a function called PosEnd
in JavaScript to place the cursor
at the end */
function PosEnd(end) {
var len = end.value.length;
// Mostly for Web Browsers
if (end.setSelectionRange) {
end.focus();
end.setSelectionRange(len, len);
} else if (end.createTextRange) {
var t = end.createTextRange();
t.collapse(true);
t.moveEnd('character', len);
t.moveStart('character', len);
t.select();
}
}
</script>
</body>
</html>
输出: