表單輸入框的視覺回饋對使用者體驗至關重要。本文介紹如何使用 jQuery 實現滑鼠懸進/移出時動態切換邊框顏色,並探討現代 CSS 原生方案的優勢。
$(document).ready(function() {
// 1. 設定預設樣式
$('input:text').attr('style', 'border: 1px solid #7E9DB9;');
// 2. 滑鼠進入:高亮邊框
$('input:text').mouseover(function() {
$(this).attr('style', 'border: 1px solid #EDBB72;');
});
// 3. 滑鼠離開:恢復預設
$('input:text').mouseout(function() {
$(this).attr('style', 'border: 1px solid #7E9DB9;');
});
});
input:text 等同 input[type="text"],僅針對文字輸入框.attr('style', ...) 直接設定內聯樣式,優先級最高mouseover/mouseout 配對使用,注意冒泡特性<style>
.input-default { border: 1px solid #7E9DB9; }
.input-hover { border: 1px solid #EDBB72; }
.input-focus { border: 1px solid #FF6B35; box-shadow: 0 0 0 3px rgba(255,107,53,0.2); }
</style>
<script>
$(function() {
$('input:text')
.addClass('input-default')
.on('mouseenter', function() { $(this).addClass('input-hover'); })
.on('mouseleave', function() { $(this).removeClass('input-hover'); })
.on('focus', function() { $(this).addClass('input-focus'); })
.on('blur', function() { $(this).removeClass('input-focus input-hover'); });
});
</script>
<style>
.form-input {
border: 1px solid #7E9DB9;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
padding: 8px 12px;
border-radius: 4px;
}
.form-input:hover {
border-color: #EDBB72;
}
.form-input:focus {
outline: none;
border-color: #FF6B35;
box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.2);
}
.form-input:disabled {
background: #f5f5f5;
cursor: not-allowed;
}
</style>
<input type="text" class="form-input" placeholder="請輸入內容">
| 維度 | jQuery 內聯樣式 | jQuery 類別切換 | 純 CSS |
|---|---|---|---|
| 程式碼量 | 少 | 中 | 最少 |
| 效能 | 較差(強制重排) | 中等 | 最佳(GPU 加速) |
| 維護性 | 差(樣式分散在 JS) | 良好 | 最佳(樣式集中管理) |
| 動畫支援 | 需額外代碼 | 需額外代碼 | 原生 transition |
| 動態主題切換 | 困難 | 中等 | CSS 變數極易實現 |
| 舊瀏覽器相容 | 最好 | 好 | 需 Polyfill |
:valid/:invalid 偽類搭配 required、pattern 屬性maxlength + JS 即時顯示剩餘字數:-webkit-autofill 樣式自定義outline: none 必須提供替代視覺提示)