假设我们有一个代表用户全名的文本字段。还有一个用于更新全名的编辑按钮。
<input type="text" id="fullName" />
<button id="edit">Edit</button>
有一个常见的要求是单击编辑按钮将焦点放在文本字段上,并将光标移动到它的末尾:
const fullNameEle = document.getElementById('fullName');
const editEle = document.getElementById('edit');
editEle.addEventListener('click', function (e) {
// Focus on the full name element
fullNameEle.focus();
// Move the cursor to the end
const length = fullNameEle.value.length;
fullNameEle.setSelectionRange(length, length);
});