DIV CSS 佈局教程網

js 修改 input 的 type 屬性:IE 的限制與替代方案
編輯:關於JavaScript     

用 JavaScript 改 input 的 type,其實是有條件限制的。當元素還沒插入文件流之前,改它的 type 沒問題,IE 與 Firefox 都支援;但一旦元素已經存在於頁面上,IE 就把 type 當成唯讀屬性,改不動,而 Firefox 仍然可讀可寫。

一個實際需求

輸入框有預設文字「密碼」,取得焦點時文字消失,開始輸入後直接變成圓點的 password 型態。也就是說,input 一開始是 text,之後要變成 password。最直覺的想法是改 type,但在 IE 下行不通,於是換個思路:放兩個 input,一個 text、一個 password,分別監聽 onfocus 與 onblur,用顯示/隱藏來切換。

完整範例

注意:script 這段要寫在 HTML 裡面(放在元素之後),才能保證 getElementById 抓得到。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>輸入框提示文字切換</title>
</head>
<body>
<input name="" type="text" value="密碼" class="inputText_1" id="tx" style="width:100px;" />
<input name="" type="password" style="display:none;width:100px;" id="pwd" />
<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>
</body>
</html>

觀念整理

這個方案的關鍵細節有三個:一是 pwd.focus() 必須在顯示之後呼叫,焦點才不會掉;二是 onblur 只在 pwd 為空時才退回提示文字,避免把使用者輸入的密碼清掉;三是兩個欄位要設一樣的寬度,切換時版面才不會跳動。

今天的做法通常會用 HTML5 的 placeholder 屬性取代這整套技巧,若要相容舊版 IE,才需要像上面這樣手動切換。

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