萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

HTML5 表單輸入框聚焦/懸停變色效果:CSS 狀態樣式完整指南

效果展示

輸入框四種狀態視覺回饋:

  • 預設:灰邊框、白底
  • 懸停:深灰邊框、淡黃底
  • 聚焦:藍邊框、淡黃底、外發光
  • 離開後:恢復預設(若有值保持填寫狀態樣式)

原始代碼問題分析

  • 使用內聯事件屬性 onfocus, onblur, onmousemove, onmouseout 切換 class
  • 邏輯分散在 HTML 中,難以維護
  • this.onmouseout = function()... 覆蓋導致行為不一致
  • 無鍵盤無障礙支援

現代純 CSS 實作(零 JavaScript)

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表單輸入框狀態樣式</title>
    <style>
        * { box-sizing: border-box; }
        body { font: 16px/1.5 system-ui, sans-serif; padding: 2rem; background: #fafafa; }
        
        .form-group { margin-bottom: 1.5rem; max-width: 400px; }
        .form-label { 
            display: block; margin-bottom: 0.5rem; 
            font-weight: 500; color: #333; 
        }
        .form-hint { 
            display: block; margin-top: 0.375rem; 
            font-size: 0.875rem; color: #666; 
        }
        
        /* 核心輸入框樣式 */
        .form-input {
            width: 100%;
            padding: 0.625rem 0.875rem;
            font: inherit;
            color: #1a1a1a;
            background: #fff;
            border: 2px solid #d1d5db;
            border-radius: 6px;
            outline: none;
            transition: border-color 0.15s ease, box-shadow 0.15s ease, background-color 0.15s ease;
        }
        
        /* 懸停狀態 */
        .form-input:hover:not(:focus):not(:disabled) {
            border-color: #9ca3af;
            background: #fefce8; /* 淡黃 */
        }
        
        /* 聚焦狀態 - 最高優先級 */
        .form-input:focus {
            border-color: #3b82f6;
            background: #fefce8;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.25);
        }
        
        /* 有值狀態(離開後保持) */
        .form-input:not(:placeholder-shown) {
            background: #fefce8;
            border-color: #9ca3af;
        }
        .form-input:not(:placeholder-shown):focus {
            background: #fefce8;
        }
        
        /* 禁用狀態 */
        .form-input:disabled {
            background: #f3f4f6; color: #9ca3af; cursor: not-allowed;
        }
        
        /* 錯誤狀態 */
        .form-input[aria-invalid="true"] {
            border-color: #ef4444;
            background: #fef2f2;
        }
        .form-input[aria-invalid="true"]:focus {
            box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.25);
        }
        
        /* 成功狀態 */
        .form-input[aria-describedby*="success"] {
            border-color: #22c55e;
        }
    </style>
</head>
<body>
    <form class="form">
        <div class="form-group">
            <label class="form-label" for="name">姓名</label>
            <input type="text" class="form-input" id="name" placeholder="請輸入您的姓名" aria-describedby="name-hint">
            <span class="form-hint" id="name-hint">請輸入真實姓名</span>
        </div>
        
        <div class="form-group">
            <label class="form-label" for="email">Email</label>
            <input type="email" class="form-input" id="email" placeholder="請輸入您的 Email" aria-describedby="email-hint">
            <span class="form-hint" id="email-hint">我們不會公開您的信箱</span>
        </div>
        
        <div class="form-group">
            <label class="form-label" for="website">個人網站</label>
            <input type="url" class="form-input" id="website" placeholder="https://example.com" aria-describedby="web-hint">
            <span class="form-hint" id="web-hint">選填</span>
        </div>
        
        <button type="submit" style="padding: 0.75rem 1.5rem; background: #3b82f6; color: #fff; border: none; border-radius: 6px; font-weight: 600; cursor: pointer;">送出</button>
    </form>
</body>
</html>

CSS 狀態優先級順序

:disabled          /* 最高:瀏覽器原生禁用樣式優先 */
:read-only         /* 僅讀 */
:focus-visible     /* 鍵盤聚焦可見焦點環(現代最佳實踐) */
:focus             /* 滑鼠/鍵盤聚焦 */
:hover             /* 滑鼠懸停 */
:not(:placeholder-shown) /* 有值狀態 */
:valid / :invalid  /* 表單驗證狀態 */
:default           /* 預設狀態 */

進階::focus-visible 只在鍵盤導航時顯示焦點環

.form-input:focus {
    /* 滑鼠點擊不顯示焦點環,僅改變邊框色 */
    border-color: #3b82f6;
    background: #fefce8;
}

.form-input:focus-visible {
    /* 鍵盤 Tab 聚焦才顯示明顯焦點環 */
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.4);
    outline: none;
}

/* 移除預設 outline 但保留無障礙 */
.form-input:focus:not(:focus-visible) {
    outline: none;
    box-shadow: none;
}

JavaScript 增強版(需動態驗證、字元計數等)

<script>
class FormInput {
    constructor(inputEl) {
        this.input = inputEl;
        this.hintEl = document.getElementById(inputEl.getAttribute('aria-describedby'));
        this.bindEvents();
    }
    
    bindEvents() {
        this.input.addEventListener('input', () => this.validate());
        this.input.addEventListener('blur', () => this.showError());
        this.input.addEventListener('focus', () => this.clearError());
    }
    
    validate() {
        const val = this.input.value.trim();
        const type = this.input.type;
        let valid = true;
        let message = '';
        
        if (this.input.required && !val) {
            valid = false; message = '此欄位為必填';
        } else if (type === 'email' && val && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)) {
            valid = false; message = 'Email 格式不正確';
        } else if (type === 'url' && val && !/^https?:\/\//.test(val)) {
            valid = false; message = '請輸入完整網址 (含 https://)';
        }
        
        this.input.setAttribute('aria-invalid', !valid);
        if (this.hintEl) this.hintEl.textContent = message || this.hintEl.dataset.original;
        return valid;
    }
    
    showError() { this.validate(); }
    clearError() { 
        this.input.removeAttribute('aria-invalid'); 
        if (this.hintEl) this.hintEl.textContent = this.hintEl.dataset.original;
    }
}

// 初始化
document.querySelectorAll('.form-input').forEach(input => {
    if (input.getAttribute('aria-describedby')) {
        const hint = document.getElementById(input.getAttribute('aria-describedby'));
        if (hint) hint.dataset.original = hint.textContent;
    }
    new FormInput(input);
});

// 表單送出驗證
document.querySelector('form').addEventListener('submit', e => {
    let allValid = true;
    document.querySelectorAll('.form-input').forEach(input => {
        if (!new FormInput(input).validate()) allValid = false;
    });
    if (!allValid) e.preventDefault();
});
</script>

無障礙檢查清單

  • [ ] 每個輸入框有關聯的 <label for="id">
  • [ ] aria-describedby 指向提示/錯誤訊息元素
  • [ ] 必填欄位 required + aria-required="true"
  • [ ] 錯誤訊息 role="alert" 或 aria-live="polite"
  • [ ] :focus-visible 焦點環符合 3:1 對比度
  • [ ] 色彩非唯一資訊傳遞(需配合圖示/文字)
  • [ ] 自動完成 autocomplete="name/email/url/off" 正確設定

瀏覽器支援現況

特性ChromeFirefoxSafariEdge
:focus-visible86+85+15.4+86+
:placeholder-shown47+51+10.1+79+
:not(:placeholder-shown)同左同左同左同左
CSS 變數49+31+9.1+79+
copyright © 萬盛學電腦網 all rights reserved