起因
当用户首次进入页面,在input
或textarea
中已有内容的情况下,同时又需要修改内容的时候。我们想给用户更好的体验,那么就想到了在进入页面的时候将光标自动聚焦的文本上,减少用户的操作并提示用户需要输入内容。
问题
但是在使用时有一点小bug,那就是光标闪烁的位置并不在末尾,而是在开头:
原始代码:
<body>
<input type="text" value="你快乐吗" />
<textarea cols="10" rows="3">我不快乐</textarea>
</body>
<script>
const input = document.querySelector('input')
input.focus()
const textarea = document.querySelector('textarea')
textarea.focus()
</script>
input
:
textarea
:
这样的效果当然不是我们想要的
解决方案
- 省流:该方法的两个参数均为
-1
即可:input.setSelectionRange(-1, -1)
当然也有相应的解决方法,那就是setSelectionRange方法
HTMLInputElement.setSelectionRange
方法用于设定<input>
或 <textarea>
元素中当前选中文本的起始和结束位置。
语法:element.setSelectionRange(selectionStart, selectionEnd [, selectionDirection]);
参数
如果 selectionEnd
小于 selectionStart
,则二者都会被看作 selectionEnd
。
-
selectionStart
被选中的第一个字符的位置索引,从0开始。如果这个值比元素的
value
长度还大,则会被看作value
最后一个位置的索引。 -
selectionEnd
被选中的最后一个字符的 下一个 位置索引。如果这个值比元素的value长度还大,则会被看作value最后一个位置的索引。
-
selectionDirection
可选一个表示选择方向的字符串,可能的值有:
-
"forward"
-
"backward"
-
"none"
默认值,表示方向未知或不相关。
修改后的代码
<body>
<input type="text" value="你快乐吗" />
<textarea cols="10" rows="3">我不快乐</textarea>
</body>
<script>
const input = document.querySelector('input')
input.focus()
+ input.setSelectionRange(-1, -1)
const textarea = document.querySelector('textarea')
textarea.focus()
+ textarea.setSelectionRange(-1, -1)
</script>
input
textarea
成功解决了文本框聚焦的需求