輸入框是表單交互的核心,靈活運用 CSS 與少量 JS 可打造豐富視覺回饋。匯總 7 類經典樣式模式,開箱即用。
<input style="background: transparent; border: 1px solid #fff; color: #fff;">
適用深色背景頁面,配合 `::placeholder` 設定提示色。
<input type="text" value="Type here"
onmouseover="this.style.borderColor='#000'; this.style.backgroundColor='#dda0dd';"
onmouseout="this.style.borderColor='#000'; this.style.backgroundColor='#fff';"
style="border:1px solid #000; width:106px; height:21px;">
現代寫法改用 CSS `:hover`、`:focus` 偽類,結構行為分離。
<style>
#flashInput { border: 2px dotted #f00; color: #f00; }
#flashInput:focus { animation: flashBorder 0.8s infinite alternate; }
@keyframes flashBorder {
from { border-color: #f00; } to { border-color: #ff0; }
}
</style>
<input type="text" id="flashInput">
CSS Animation 替代 JS `setTimeout`,效能更好、無記憶體洩漏風險。
<input type="text" style="width: auto; min-width: 50px;" value="abcdefghijk">
配合 `width: auto` + `min-width`,內容撐開寬度。舊 IE `expression` 方案已廢棄 (安全風險、效能差)。
<textarea oninput="this.style.height='auto'; this.style.height=this.scrollHeight+'px'"
rows="3" style="min-height: 60px; resize: vertical;"></textarea>
輸入時動態調整高度,`resize: vertical` 允許用戶手動拖拽。
<input style="border: none; border-bottom: 2px solid #333; background: transparent; outline: none; padding: 8px 0;">
配合 `:focus { border-bottom-color: #1976d2; }` 實現 Material 風聚焦態。
<style>
.serial-group input { width: 3ch; text-align: center; border: 1px solid #ccc; margin: 0 2px; }
.serial-group input:focus { outline: none; border-color: #1976d2; box-shadow: 0 0 0 2px rgba(25,118,210,.2); }
</style>
<div class="serial-group">
<input maxlength="4"> - <input maxlength="4"> - <input maxlength="4"> - <input maxlength="4">
</div>
<script>
document.querySelectorAll('.serial-group input').forEach((el, i, arr) => {
el.addEventListener('input', () => {
if (el.value.length === el.maxLength && i < arr.length-1) arr[i+1].focus();
});
el.addEventListener('keydown', e => {
if (e.key === 'Backspace' && !el.value && i > 0) arr[i-1].focus();
});
});
</script>
自動跳轉焦點、退格回退,極佳體驗。
<form onsubmit="event.preventDefault(); alert([...document.querySelectorAll('.serial-group input')].map(i=>i.value).join('-'));">
<div class="serial-group">...</div>
<button type="submit">提交</button>
</form>
所有樣式均遵循**漸進增強**:基礎功能無 JS 可用,JS 僅增強體驗。