如何使用 CSS 建立一個動畫搜尋表單?


如今,許多網站都在主頁上內建了一個動畫搜尋框。當將滑鼠游標移到搜尋框內時,搜尋框的寬度變大,從而使使用者更容易進行搜尋。讓我們瞭解如何使用 HTML 和 CSS 建立這種動畫搜尋表單。

建立搜尋表單

使用 <form>元素,並在其中放置輸入型別文字。別忘了為使用者新增一個適合的佔位符,以便使用者瞭解文字框的用途−

<form>
   Search:
   <input type="text" name="search" placeholder="Search Here...">
</form>

給搜尋框新增樣式

搜尋框樣式如下。此外,還使用 width 屬性上的 transition 屬性設定過渡。過渡時間功能設定為 ease-in-out,即開始和結束較慢的過渡−

input[type=text] {
   width: 170px;
   font-size: 16px;
   background-color: white;
   padding: 12px 20px 12px 40px;
   transition: width 0.4s ease-in-out;
}

給搜尋表單新增動畫

使用 :focus 選擇器,在設定焦點時,寬度將變為 100%。:focus 選擇器選擇擁有焦點的元素−

input[type=text]:focus {
   width: 100%;
}

示例

以下程式碼使用 CSS 建立了一個動畫搜尋表單−

<!DOCTYPE html>
<html>
<head>
   <style>
      *{
         box-sizing: border-box;
      }
      input[type=text] {
         width: 170px;
         font-size: 16px;
         background-color: white;
         padding: 12px 20px 12px 40px;
         transition: width 0.4s ease-in-out;
      }
      input[type=text]:focus {
         width: 100%;
      }

   </style>
</head>
<body>
   <h1>Animated search form example</p>
   <form>
      Search:
      <input type="text" name="search" placeholder="Search Here...">
   </form>
</body>
</html>

更新於: 2023-12-14

209 次瀏覽

開啟你的 職業生涯

獲得認證以完成課程

開始
廣告