使用 JavaScript 将光标设置在文本区域的末尾
将光标设置在文本区域的末尾:
-
使用
setSelectionRange()
方法将当前文本选择位置设置为文本区域的末尾。 -
在
textarea
元素上调用focus()
方法。 -
focus
方法会将光标移动到元素值的末尾。
以下是本文示例的 HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<textarea id="message" rows="5" cols="30">Initial text here</textarea>
<button id="btn">Move cursor to beginning</button>
<script src="index.js"></script>
</body>
</html>
这是相关的 JavaScript 代码。
const textarea = document.getElementById('message');
const end = textarea.value.length;
// ✅ Move focus to End of textarea
textarea.setSelectionRange(end, end);
textarea.focus();
// ✅ Move focus to End of textarea on button click
const btn = document.getElementById('btn');
btn.addEventListener('click', function handleClick() {
// 👇️ get length right before clicking button
const end = textarea.value.length;
textarea.setSelectionRange(end, end);
textarea.focus();
});
我们使用 setSelectionRange
来设置 textarea 元素中当前文本选择的开始和结束位置。
我们传递给 setSelectionRange
方法的两个参数是:
- selectionStart - 第一个选定字符的从零开始的索引。
- selectionEnd - 最后一个选定字符之后字符的从零开始的索引。
大于文本区域值长度的索引指向值的末尾。
最后一步是调用元素的 focus()
方法。
焦点元素将光标移动到调用该方法的元素。
这个想法是根本不选择任何文本,而是将光标移动到文本区域值的末尾并将其聚焦。
单击按钮时将光标设置在文本区域的末尾:
- 将点击事件侦听器添加到按钮元素。
-
每次单击按钮时,都会对文本区域元素调用
setSelectionRange()
方法。 -
调用
focus()
方法将光标移动到文本区域的末尾。
const textarea = document.getElementById('message');
// ✅ Move focus to End of textarea on button click
const btn = document.getElementById('btn');
btn.addEventListener('click', function handleClick() {
const end = textarea.value.length;
textarea.setSelectionRange(end, end);
textarea.focus();
});
每次单击按钮时,都会调用 handleClick
函数,我们在其中:
- 将文本区域中的文本选择设置到其最后一个字符之后的位置。
- 聚焦元素。
请注意
,我们在单击按钮时立即获得了元素值的长度。 这可确保最终变量中的值始终是最新的。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。