DIV CSS 佈局教程網

IE 下 input.type 唯讀的相容問題,以及雙輸入框的解法
編輯:關於JavaScript     

問題背景

用 JavaScript 修改 input 的 type 屬性其實是有規矩的:當元素尚未插入文件流時,type 可以自由修改,IE 與 Firefox 都沒問題。但一旦 input 已經存在於頁面上,type 在 IE 中就變成唯讀屬性,改不動;Firefox 則仍視為可讀寫。

實際遭遇的需求

今天遇到的情況是這樣:輸入框有預設文字「密碼」,但當它獲得焦點時,「密碼」兩字會消失,使用者輸入的內容則直接以 **** 呈現。也就是說,input 的類型需要在 text 與 password 之間切換。

最直觀的思路是用 JS 改 type,但在 IE 下這條路走不通,只能換個角度:準備兩個 input,一個 text、一個 password,分別監聽 onfocus 與 onblur 來切換顯示。

解法程式碼

<input name="" type="text" value="密碼" id="tx" style="width:100px;" />
<input name="" type="password" id="pwd" style="display:none;width:100px;" />

<script type="text/javascript">
var tx  = document.getElementById("tx"),
    pwd = document.getElementById("pwd");

tx.onfocus = function () {
  if (this.value != "密碼") return;   // 使用者已改過內容就不處理
  this.style.display = "none";
  pwd.style.display  = "";
  pwd.value = "";
  pwd.focus();                        // 把焦點交給密碼框
};

pwd.onblur = function () {
  if (this.value != "") return;       // 有輸入內容就保持密碼框
  this.style.display = "none";
  tx.style.display  = "";
  tx.value = "密碼";                  // 還原提示文字
};
</script>

運作流程

初始狀態只有 text 框可見,顯示灰色提示字「密碼」。使用者點進去(focus)時,若內容仍是提示文字,就把 text 框藏起來、顯示 password 框並交給它焦點,於是接下來輸入的內容會被圓點遮蔽。

當 password 框失去焦點(blur)時,若內容為空,就切回 text 框並把提示文字填回去;若使用者確實輸入過密碼,則保留 password 框,讓已輸入的內容不遺失。

幾個可以再加強的地方

其一,兩個 input 都必須設定相同的 name,否則表單送出時只會帶到其中一個欄位,後端會拿不到值。

其二,提示文字寫在 value 裡,使用者全選刪除後再離開,提示不會回來。若要更穩健,可改用 placeholder="密碼" 屬性——現代瀏覽器原生支援,且不會送出到後端,省掉所有判斷邏輯:

<input type="password" name="pwd" placeholder="密碼" style="width:100px;" />

在需要相容 IE8 以下的年代,本文的雙輸入框是標準解法;而在今天,placeholder 加上一段輕量的 polyfill 才是更乾淨的選擇。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved