萬盛學電腦網

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

DOM 文本框進階控制:字數限制、自動選中、聚焦管理最佳實踐

前言

<input type="text">、<input type="password">、<textarea> 是用戶輸入的核心介面。本文聚焦三大高頻需求:字數限制、滑鼠經過自動選中、聚焦/失焦行為優化,提供原生 DOM 實現方案並對比 HTML5 原生屬性優缺點。

一、字數限制

方案 A:HTML5 原生 maxlength(推薦)

<!-- 單行輸入框:原生支援,瀏覽器自動阻止輸入 -->
<input type="text" name="username" maxlength="20">

<!-- 多行文本域:HTML5 同樣支援 maxlength -->
<textarea name="bio" maxlength="200"></textarea>
  • ✅ 零 JS、效能最佳、無障礙友善
  • ✅ 瀏覽器原生顯示剩餘字數(部分瀏覽器)
  • ⚠️ 無法自定義超限提示、無法統計「字符」vs「位元組」差異

方案 B:JS 即時統計與提示(彈性最高)

<textarea id="comment" rows="4" cols="50" data-maxlen="200"></textarea>
<div class="counter"><span id="currentLen">0</span> / 200</div>

<script>
var textarea = document.getElementById('comment');
var maxLen = parseInt(textarea.dataset.maxlen, 10);
var counter = document.getElementById('currentLen');

function updateCounter() {
  var len = textarea.value.length;
  counter.textContent = len;
  counter.style.color = len > maxLen ? '#dc3545' : '';
}

textarea.addEventListener('input', updateCounter);
// 初始化
updateCounter();
</script>

方案 C:硬性截斷(防止繞過)

textarea.addEventListener('input', function () {
  if (this.value.length > maxLen) {
    this.value = this.value.slice(0, maxLen);
    updateCounter();
  }
});

二、滑鼠經過自動聚焦與全選

行內事件寫法(簡單但不推薦)

<input type="text" value="預設文字"
       onmouseover="this.focus()"
       onfocus="this.select()">

非侵入式 JS 綁定(推薦)

<input type="text" id="username" name="username" value="請輸入帳號">
<input type="password" id="password" name="password">

<script>
function setupAutoSelect(inputId) {
  var el = document.getElementById(inputId);
  if (!el) return;

  // 滑鼠進入 → 聚焦
  el.addEventListener('mouseover', function () {
    // 避免移動端誤觸發:僅非觸控設備
    if (!('ontouchstart' in window)) this.focus();
  });

  // 獲得焦點 → 全選(方便覆蓋輸入)
  el.addEventListener('focus', function () {
    // 僅當值等於預設提示文字時全選,避免用戶編輯中途被全選
    if (this.value === this.defaultValue || this.dataset.placeholder === 'true') {
      this.select();
    }
  });

  // 失焦 → 若為空恢復提示(可選)
  el.addEventListener('blur', function () {
    if (!this.value) {
      this.value = this.defaultValue;
      this.dataset.placeholder = 'true';
    }
  });
}

setupAutoSelect('username');
setupAutoSelect('password');
</script>

三、批量綁定多個輸入框

<form id="loginForm">
  <input type="text" name="account" placeholder="帳號">
  <input type="password" name="pwd" placeholder="密碼">
  <input type="text" name="captcha" placeholder="驗證碼">
</form>

<script>
var form = document.getElementById('loginForm');

Array.from(form.elements).forEach(function (el) {
  if (el.tagName === 'INPUT' && /text|password|email|search|tel|url/.test(el.type)) {
    el.addEventListener('mouseover', function () {
      if (!('ontouchstart' in window)) this.focus();
    });
    el.addEventListener('focus', function () {
      this.select();
    });
  }
});
</script>

四、進階體驗優化

1. 佔位符 placeholder vs value 預設值

特性placeholdervalue (預設值)
語義提示範例格式預填實際數據
提交行為不提交會提交
樣式控制::placeholder 偽元素普通文字樣式
適用場景格式提示(如「手機號」)預填用戶已有資料

2. 密碼顯示/隱藏切換

<div class="pwd-wrapper">
  <input type="password" id="pwd" name="pwd">
  <button type="button" class="toggle-pwd" aria-label="顯示密碼">👁</button>
</div>

<script>
document.querySelector('.toggle-pwd').addEventListener('click', function () {
  var pwd = document.getElementById('pwd');
  var isPwd = pwd.type === 'password';
  pwd.type = isPwd ? 'text' : 'password';
  this.textContent = isPwd ? '🙈' : '👁';
  this.setAttribute('aria-label', isPwd ? '隱藏密碼' : '顯示密碼');
});
</script>

3. 自動調整 textarea 高度

function autoResize(textarea) {
  textarea.style.height = 'auto'; // 重置
  textarea.style.height = textarea.scrollHeight + 'px';
}

var ta = document.querySelector('textarea[data-auto-resize]');
if (ta) {
  ta.addEventListener('input', function () { autoResize(this); });
  autoResize(ta); // 初始化
}

五、無障礙檢查清單

  • [ ] 每個輸入框有關聯 <label>(for/id 或包裹)
  • [ ] 必填項標記 required + aria-required="true"
  • [ ] 錯誤訊息掛載 aria-describedby 指向錯誤元素
  • [ ] autocomplete 屬性正確(username/current-password/new-password/off)
  • [ ] 移動端 inputmode 提示正確鍵盤(numeric/email/tel)

結語

文本框控制看似瑣碎,實則直接影響用戶輸入效率與錯誤率。優先使用 HTML5 原生屬性(maxlength、placeholder、required),輔以輕量 JS 增強體驗(自動全選、計數提示、高度自適應),並嚴守無障礙規範,即可構建專業級輸入體驗。

copyright © 萬盛學電腦網 all rights reserved