如何使用 JavaScript 將游標位置設定在文字輸入欄位的末尾?


在 HTML 中,輸入欄位用於接收使用者的輸入。有時,我們需要在輸入中接收字串或長文字訊息。在這些情況下,使用者可能需要轉到輸入欄位的末尾以新增更多內容或訊息。因此,我們應該設定一些內容,以便使用者可以單擊按鈕,然後轉到輸入欄位的末尾。在本教程中,我們將學習如何使用 JavaScript 將游標位置設定在輸入欄位文字的末尾。

使用 setSelectionRange() 方法

setSelectionRange() 方法用於選擇輸入欄位中的文字。它需要兩個引數來開始和結束選擇。我們可以使用 setSelectionRange() 方法選擇最後一個字元,從而將游標放在文字的末尾。

語法

使用者可以按照以下語法使用 setSelectionRange() 方法將游標放在文字的末尾。

input.setSelectionRange(len, len);

在上面的語法中,input 是我們在 JavaScript 中訪問的 HTML 元素。“len”是輸入值的長度。

示例

在下面的示例中,我們建立了輸入欄位和按鈕。當用戶單擊按鈕時,它將執行 moveAtend() 函式。

在 JavaScript 中,我們定義了 moveAtend() 函式,它訪問“name”輸入欄位。之後,它使用 focus() 方法將焦點設定在輸入欄位上。之後,我們透過將輸入值的長度作為兩個引數傳遞來使用 setSelectionRange() 方法。在輸出中,使用者可以單擊按鈕並觀察它將游標位置設定在文字的末尾。

<html>
   <body>
      <h3> Using the <i> setSelectionRange() method </i> to move the cursor at the end of the input field in JavaScript </h3>
      <input type = "text" id = "name" value = "Shubham">
      <button onclick = "moveAtend()"> Move cursor at end </button>
      <script>
         let output = document.getElementById("output");
         function moveAtend() {
         let name = document.getElementById("name");
         name.focus();
         name.setSelectionRange(name.value.length, name.value.length);
         }
      </script>
</html>

使用 selectionStart 和 selectionEnd 屬性

“selectionStart”和“selectionEnd”CSS 屬性用於選擇輸入欄位中的輸入值。“selectionStart”獲取從哪裡開始選擇的索引值,“selectionEnd”獲取我們需要結束文字選擇的位置的索引值。

在這裡,我們可以將“selectionStart”和“selectionEnd”屬性的值設定為文字長度,以將游標放在文字的末尾。

語法

使用者可以按照以下語法使用“selectionStart”和“selectionEnd”屬性將游標放在文字的末尾。

input.selectionStart = len;
input.selectionEnd = len;

在上面的語法中,input 是一個 HTML 元素,“len”是其值的長度。

示例

與第一個示例一樣,我們在下面的示例中建立了輸入欄位。在 moveAtend() 函式中,我們為“name”輸入欄位將“selectionStart”和“selectionEnd”屬性的值設定為文字長度。

<html>
   <body>
      <h3> Using the <i> selectionStart and selectionEnd Properties </i> to move the cursor at the end of the input field in JavaScript </h3>
      <input type = "text" id = "name" value = "Shubham">
      <button onclick = "moveAtend()"> Move cursor at end </button>
      <script>
         let output = document.getElementById("output");
         function moveAtend() {
         let name = document.getElementById("name");
         name.focus();
         name.selectionStart = name.value.length;
         name.selectionEnd = name.value.length;
         }
      </script>
</html>

結論

我們學習了兩種將游標放在輸入欄位文字值末尾的方法。在第一種方法中,我們使用了 setSelectionRange() 方法;在第二種方法中,我們使用了“selectionStart”和“selectionEnd”屬性。但是,這兩種方法幾乎相同,因為 setSelectionRange() 方法將“selectionStart”和“selection”結束值作為引數。

更新於:2023年5月17日

10K+ 瀏覽量

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告