HTML & CSS 中的輸入標籤動畫
在本文中,我們將使用 HTML 和 CSS 建立基本的輸入標籤動畫。我們將藉助 HTML 建立輸入標籤的結構,並藉助 CSS 設計該 HTML 結構。
什麼是輸入標籤動畫?
本文將建立的輸入標籤動畫。當用戶點選輸入欄位進行輸入時,輸入標籤名稱會移動到輸入欄位的邊框上。看起來很酷。您可以在下面給出的影像中看到它。
建立輸入標籤動畫的方法
要建立輸入標籤動畫,我們將建立兩個檔案。
用於結構的 HTML 程式碼
在此檔案中,我們將準備 HTML 的基本結構。我們將使用div 標籤、input 標籤、label 標籤等。您可以在下面給出的示例中看到這一點。
HTML 程式碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Input Label Animation</title> <link rel="stylesheet" href="mystyle.css"> </head> <body> <div class="input-container"> <input type="text" id="name" placeholder=" " required> <label for="name">Your Name</label> </div> </body> </html>
用於樣式的 CSS 程式碼
在此檔案中,我們使用了 CSS 的基本屬性。 CSS 檔案連結在 HTML 的頭部選擇中。您可以在下面給出的示例中看到 CSS 程式碼。
CSS 程式碼
* { box-sizing: border-box; } body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; font-family: Arial, sans-serif; background-color: #f0f0f0; } .input-container { position: relative; width: 250px; } input { width: 100%; padding: 10px; font-size: 16px; border: 2px solid #ccc; border-radius: 5px; outline: none; } input:focus { border-color: #4a90e2; } label { position: absolute; top: 50%; left: 10px; transform: translateY(-50%); color: #888; font-size: 16px; pointer-events: none; transition: 0.3s ease all; } /* Animation for focused input */ input:focus + label, input:not(:placeholder-shown) + label { top: 0; left: 10px; font-size: 12px; color: #4a90e2; background-color: #f0f0f0; padding: 0 5px; }
輸入標籤動畫的完整程式碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Input Label Animation</title> <style> * { box-sizing: border-box; } body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; font-family: Arial, sans-serif; background-color: #f0f0f0; } .input-container { position: relative; width: 250px; } input { width: 100%; padding: 10px; font-size: 16px; border: 2px solid #ccc; border-radius: 5px; outline: none; } input:focus { border-color: #4a90e2; } label { position: absolute; top: 50%; left: 10px; transform: translateY(-50%); color: #888; font-size: 16px; pointer-events: none; transition: 0.3s ease all; } /* Animation for focused input */ input:focus+label, input:not(:placeholder-shown)+label { top: 0; left: 10px; font-size: 12px; color: #4a90e2; background-color: #f0f0f0; padding: 0 5px; } </style> </head> <body> <div class="input-container"> <input type="text" id="name" placeholder=" " required> <label for="name">Your Name</label> </div> </body> </html>
輸出
如您所見,我們透過使用 HTML 和 CSS 建立了一個基本的輸入標籤動畫。
廣告