萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 表單輸入框焦點與預設文字控制:原生事件與 jQuery 最佳實踐

核心事件對照表

事件觸發時機常見用途
focus元素獲得焦點(點擊、Tab、.focus())清除預設提示、顯示說明、啟動編輯器
blur元素失去焦點驗證、恢復預設提示、送出表單
mouseover/mouseenter滑鼠移入顯示工具提示、預覽
mouseout/mouseleave滑鼠移出隱藏工具提示
keydown/keypress/keyup鍵盤按下/輸入/放開Enter 換焦點、Esc 取消、格式化輸入

常見互動模式與程式碼範例

模式 1:預設提示文字(Placeholder 效果)

現代做法:直接用 HTML5 placeholder 屬性,無需 JS。

<textarea placeholder="請輸入內容..."></textarea>
<input type="text" placeholder="搜尋關鍵字">

模式 2:舊瀏覽器相容 / 自訂邏輯(聚焦清空、離焦恢復)

<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>

模式 3:滑鼠進入即聚焦並清空

<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>

模式 4:點擊全選內容

<input type="text" value="預設值" onfocus="this.select()">
<textarea onfocus="this.select()">預設文字</textarea>

模式 5:Enter 鍵移動焦點到下一個欄位

<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>

jQuery 版本(專案已引用 jQuery 時)

// 推薦:集中綁定、關注點分離、支援動態新增元素
$(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();
    }
  });
});

最佳實踐總結

  1. 優先使用 placeholder:語意正確、無障礙、無需 JS、支援樣式 ::placeholder。
  2. 避免 onmouseover="focus()":滑鼠經過即強制聚焦會干擾鍵盤導航、觸控裝置體驗差。
  3. 事件綁定用 addEventListener/jQuery .on():勿用內聯 onfocus="...",利於維護與 CSP。
  4. 焦點管理無障礙:tabindex、autofocus、aria-describedby 關聯說明文字。
  5. 表單驗證:HTML5 required/pattern + JS checkValidity(),減少自訂邏輯。

CSS 樣式建議

:focus {
  outline: 2px solid #0066cc;
  outline-offset: 2px;
}
::placeholder {
  color: #999;
  opacity: 1; /* Firefox 需要 */
}
input:invalid:not(:placeholder-shown) {
  border-color: #dc3545;
}

善用原生 HTML5 屬性與現代事件模型,能以最少代碼實現最強健的表單互動體驗。

copyright © 萬盛學電腦網 all rights reserved