如何設定文字輸入游標樣式?


在HTML的文字輸入框中,您可以看到顯示在文字編輯位置的標記,稱為文字輸入游標。它也稱為文字輸入遊標。

在本教程中,我們將學習如何設定文字輸入游標的樣式。但是,我們只能更改文字輸入游標的顏色,因為現代瀏覽器不支援更改形狀。

語法

使用者可以按照以下語法使用“caret-color” CSS 屬性來更改文字輸入游標的顏色。

caret-color: color;

在上面的輸入中,“color”可以是字串格式的顏色名稱、十六進位制值、rgb 值或 HSL 值。

示例 1

在下面的示例中,我們定義了兩個文字輸入,並分別命名為“inp”和“inp1”類名。我們使用“caret-color” CSS 屬性為第一個輸入元素設定了“紅色”。

此外,我們為第二個輸入元素使用了“auto”值。在輸出中,使用者可以看到第一個輸入框中的紅色游標和第二個輸入框中的黑色游標,因為 auto 值採用瀏覽器的預設顏色,在大多數情況下為黑色。

<html>
<head>
   <style>
      .inp {
         caret-color: red;
      }
      .inp1 {
         caret-color: auto;
      }
   </style>
</head>
<body>
   <h3>Using the <i> caret-color </i> CSS property to style the text input caret</h3>
   <input type = "text" placeholder = "Write something here." class = "inp">
   <br> <br>
   <input type = "text" placeholder = "Write something here." class = "inp1">
</body>
</html>

示例 2

在下面的示例中,我們使用了“transparent”作為“color-caret” CSS 屬性的值,為游標設定透明顏色。基本上,當我們需要隱藏文字輸入游標時可以使用它。

在輸出中,使用者可以看到他們能夠在輸入框中寫入文字,但無法看到游標。

<html>
<head>
   <style>
      .inp {
         caret-color: transparent;
      }
   </style>
</head>
<body>
   <h3>Using the <i> caret-color </i> CSS property to style the text input caret</h3>
   <input type = "text" placeholder = "Your Good name" class = "inp">
</body>
</html>

示例 3

在下面的示例中,我們在 div 元素內添加了文字。之後,我們為 div 元素使用了值為 true 的“contenteditable”屬性,這使得 div 元素的內容可編輯。

在這裡,我們設定了可編輯 div 元素的文字輸入游標樣式,併為其設定了粉紅色,使用者可以在輸出中看到。

<html>
<head>
   <style>
      .test {
         caret-color: pink;
      }
   </style>
</head>
<body>
   <h3>Using the <i> caret-color </i> CSS property to style the text input caret</h3>
   <div class = "test" contenteditable = "true">
      This div is editable. Click anywhere on the text to start editing. Observe the Pink color of the cursor.
   </div>
</body>
</html>

使用者學習瞭如何使用“caret-color” CSS 屬性設定文字輸入游標的樣式。但是,一些較舊的瀏覽器也支援“caret-shape”屬性,使用它可以更改游標的形狀,但現代瀏覽器不支援。

更新於:2023年4月24日

495 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.