| 事件 | 觸發時機 | 常見用途 |
|---|---|---|
focus | 元素獲得焦點(點擊、Tab、.focus()) | 清除預設提示、顯示說明、啟動編輯器 |
blur | 元素失去焦點 | 驗證、恢復預設提示、送出表單 |
mouseover/mouseenter | 滑鼠移入 | 顯示工具提示、預覽 |
mouseout/mouseleave | 滑鼠移出 | 隱藏工具提示 |
keydown/keypress/keyup | 鍵盤按下/輸入/放開 | Enter 換焦點、Esc 取消、格式化輸入 |
現代做法:直接用 HTML5 placeholder 屬性,無需 JS。
<textarea placeholder="請輸入內容..."></textarea>
<input type="text" placeholder="搜尋關鍵字">
<textarea id="txt">預設提示文字</textarea>
<script>
const el = document.getElementById('txt');
const DEFAULT = '預設提示文字';
el.addEventListener('focus', () => {
if (el.value === DEFAULT) el.value = '';
});
el.addEventListener('blur', () => {
if (el.value === '') el.value = DEFAULT;
});
</script>
<textarea id="txt2">預設文字</textarea>
<script>
const el2 = document.getElementById('txt2');
el2.addEventListener('mouseenter', () => el2.focus()); // 觸發 focus 事件
el2.addEventListener('focus', () => {
if (el2.value === '預設文字') el2.value = '';
});
el2.addEventListener('blur', () => {
if (el2.value === '') el2.value = '預設文字';
});
</script>
<input type="text" value="預設值" onfocus="this.select()">
<textarea onfocus="this.select()">預設文字</textarea>
<input id="f1" placeholder="欄位 1">
<input id="f2" placeholder="欄位 2">
<input id="f3" placeholder="欄位 3">
<script>
document.querySelectorAll('input').forEach((el, i, arr) => {
el.addEventListener('keydown', e => {
if (e.key === 'Enter') {
e.preventDefault(); // 防止表單送出
const next = arr[i + 1];
if (next) next.focus();
}
});
});
</script>
// 推薦:集中綁定、關注點分離、支援動態新增元素
$(function () {
const DEFAULT = '請輸入樓盤名稱';
const $q = $('#q');
$q.on('focus', function () {
if (this.value === DEFAULT) this.value = '';
}).on('blur', function () {
if (this.value === '') this.value = DEFAULT;
});
// Enter 移動焦點
$('input[data-enter-next]').on('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
const selector = $(this).data('enter-next');
$(selector).focus();
}
});
});
placeholder:語意正確、無障礙、無需 JS、支援樣式 ::placeholder。onmouseover="focus()":滑鼠經過即強制聚焦會干擾鍵盤導航、觸控裝置體驗差。addEventListener/jQuery .on():勿用內聯 onfocus="...",利於維護與 CSP。tabindex、autofocus、aria-describedby 關聯說明文字。required/pattern + JS checkValidity(),減少自訂邏輯。:focus {
outline: 2px solid #0066cc;
outline-offset: 2px;
}
::placeholder {
color: #999;
opacity: 1; /* Firefox 需要 */
}
input:invalid:not(:placeholder-shown) {
border-color: #dc3545;
}
善用原生 HTML5 屬性與現代事件模型,能以最少代碼實現最強健的表單互動體驗。