2011-08-14 68 views
1

我有我的網站的一部分用戶登錄,我想文本框填充默認值,但顯然密碼文本框需要更改爲type =「密碼「在用戶點擊隱藏角色。這個國際海事組織的一個很好的例子是在蘋果的www.me.com網站上。任何有關最佳實施方式的幫助?Javascript:改變文本框的'輸入'點擊

回答

1

一種方式做,這是它...然後再在用戶輸入來控制顯示與默認值的控制,隱藏它並顯示當時的實際密碼控制。當用戶離開密碼控制時,如果她沒有真正輸入一個值,或者已經刪除了現有值,那麼重新顯示第一個控件並隱藏密碼控件。下面是示例代碼:

<html> 
<head> 
    <script language="ecmascript"> 
     function HandlePasswordOnFocus() { 
      if ("none" != TheForm.a.style.display) { 

       TheForm.a.style.display = "none"; 
       TheForm.b.style.display = "block"; 
       TheForm.b.focus(); 
      } 
     } 
     function HandlePasswordOnBlur() { 
      if ("" === TheForm.b.value) { 
       TheForm.b.style.display = "none" 
       TheForm.a.style.display = "block"; 
      } 
     } 
    </script> 
</head> 
<body> 
    <form name="TheForm"> 
    <input id="a" value="password" onfocus="HandlePasswordOnFocus()" /> 
    <input id="b" type="password" style="display: none" onblur="HandlePasswordOnBlur()" /> 
    </form> 
</body> 
</html> 
1

那麼,你的想法改變類型將工作瀏覽器。但是,IE的舊版本不允許您動態修改輸入控件的類型,從而使複雜的節點更換可能會丟失流程中的信息。相反,您應該使用新的HTML5 placeholder屬性,該屬性在每個瀏覽器中都不起作用,但比您執行此替換所需的腳本更加明顯和精簡。它易於使用:

<input type="password" name="pwd" value="" placeholder="Enter your password." /> 

它與Firefox 3.7或更高版本,Chrome和Safari 4或更高版本以及IE9或更高版本兼容。

+0

非常好。這應該可行,非HTML5瀏覽器會發生什麼? – Zakman411

+0

@ Zakman411:佔位符文本不會顯示。沒有什麼會打破。它優雅地退化。 – Ryan

1

如果你想改變類型,你可以簡單地使用javascript函數來改變它,當用戶點擊文本框。

<script type="text/javascript"> 
function changeType() { 
    document.getElementById("password").type = "password"; 
    document.getElementById("password").value = ""; 
} 
</script> 
<input type="text" id="password" name="password" value="Password" onClick="changeType()" /> 

但是,正如其他海報建議的 - 考慮使用佔位符屬性。

+0

在IE中失敗失敗(因爲在通常會打破腳本的其餘部分),所以要警告...... – Ryan

1

例如:http://jsfiddle.net/n3SPH/

<label for="placeholder">Password:</label> 
<input type="text" id="placeholder" value="Enter password here" onFocus="setPass();"/> 
<input type="password" id="password" value="" onBlur="checkPass();" style="display: none;"/> 

JS:

function setPass() { 
    document.getElementById('placeholder').style.display = 'none'; 
    document.getElementById('password').style.display = 'inline'; 
    document.getElementById('password').focus(); 
} 
function checkPass() { 
    if (document.getElementById('password').value.length == 0) { 
     document.getElementById('placeholder').style.display = 'inline'; 
     document.getElementById('password').style.display = 'none'; 
    } 
} 
+0

這工作,但打破了形式:/ id的都檢查和以前一樣,但現在按登錄什麼都不做。 。爲什麼? – Zakman411

+0

@ Zakman411:請記住,這個示例代碼沒有命名輸入控件 - 添加適當的'name'屬性。 (當然,如果表單實際上沒有提交提交的跡象,那麼這不是你的問題......) – Ryan

1

的方式在蘋果的Me.com做是他們設置的輸入字段是透明的,然後有一個背後的DIV他們想要顯示的文字。當某人開始在該字段中輸入時,他們會隱藏該標籤的後面。

如果你不想使用placeholder=""像其他人所建議的(我不知道爲什麼蘋果公司不會這麼做,因爲Safari支持它?),另一種方法是將圖像加載爲該字段的背景以及所需的佔位符文本,然後在某人開始輸入時爲其添加一個帶有background:none CSS屬性的類。這將需要更少的額外標記(但在Photoshop中更多修補程序...)。

相關問題