html-input/textarea聚焦focus問題


起因

當用戶首次進入頁面,在inputtextarea中已有內容的情況下,同時又需要修改內容的時候。我們想給用戶更好的體驗,那么就想到了在進入頁面的時候將光標自動聚焦的文本上,減少用戶的操作並提示用戶需要輸入內容。

問題

但是在使用時有一點小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:

image

textarea:

image

這樣的效果當然不是我們想要的

解決方案

  • 省流:該方法的兩個參數均為-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

image

textarea

image

成功解決了文本框聚焦的需求


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM